MathGroup Archive 2004

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Find last NZ in list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg46129] Re: [mg46102] Find last NZ in list
  • From: János Löbb <janos.lobb at yale.edu>
  • Date: Sat, 7 Feb 2004 04:02:13 -0500 (EST)
  • References: <200402060915.EAA19244@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

You might want to look at:
a = {a1, a2, a3, a4, a5, a6, 0, a8 - a8, a9 - a9, 0}
First[Position[a, _?(# == 0 &)]] - 1
{6}

Be aware of its ugliness for all zero list:
b = {0, 0, 0, 0, 0, 0, 0, 0, 0}
First[Position[b, _?(# == 0 &)]] - 1
\!\(\*
   RowBox[{\(First::"first"\), \(\(:\)\(\ \)\), "\<\"\\!\\({}\\)
     has a length of zero and no first
     element. \\!\\(\\*ButtonBox[\\\"More?\\\", \
ButtonStyle->\\\"RefGuideLinkText\\\", ButtonFrame->None, \
ButtonData:>\\\"First::first\\\"]\\)\"\>"}]\)

-1 + First[{}]

Try similar pattern matchings to find the right one for both cases.
János
On Feb 6, 2004, at 4:15 AM, Carlos Felippa wrote:

> This is kind of an "esthetics" question.  In a program I am writing
> I need to find the last nonzero entry of a  1D list millions of
> times.  For example FindLastNonzero[{1,2,3,4,0,a,b-b,0,0}] -> 6,
> and FindLastNonzero[{0,0,0,0,0,0,0}] -> 0.
> Here are two ugly C-style implementations:
>
> FindLastNonzero[a_]:=Module[{n=Length[a]},
>      For [i=n,i>0,i--, If [a[[i]]==0,Continue[],Return[i],Return[i]]];
>      Return[0]];
>
> FindLastNonzero[a_]:=Module[{n=Length[a]},
>      For [i=n,i>0,i--, If [a[[i]]!=0,Return[i],Continue[i],Return[i]]];
>      Return[0]];
>
> Is there a built-in function, or something more elegant,
> available to do this job?  Find only works for text streams.
>
> Note that the If case "cannot tell if  entry is NZ" is important for
> symbolic lists.  That case should be evaluated as NZ.
>
>
-------------------------------------------------
clear perl code is better than unclear awk code; but NOTHING comes 
close to unclear perl code
http://www.faqs.org/faqs/computer-lang/awk/faq/


  • Prev by Date: Re: simplifying first-order diff eq solution
  • Next by Date: Re: InputAutoReplacements With "-marks
  • Previous by thread: Re: Find last NZ in list
  • Next by thread: Re: Find last NZ in list