       Re: Find last NZ in list

• To: mathgroup at smc.vnet.net
• Subject: [mg46126] Re: [mg46102] Find last NZ in list
• From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
• Date: Sat, 7 Feb 2004 04:02:08 -0500 (EST)
• References: <200402060915.EAA19244@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```On 6 Feb 2004, at 10:15, 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];
>
> FindLastNonzero[a_]:=Module[{n=Length[a]},
>      For [i=n,i>0,i--, If [a[[i]]!=0,Return[i],Continue[i],Return[i]]];
>      Return];
>
> 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.
>
>
>

You can usually improve performance in Mathematica by using a Do loop
instead of a For loop. So in this case:

FindLastNonzero1[l_] := Catch[Do[If[l[[i]] =!=
0, Throw[i]], {i, Length[l], 1, -1}]; 0]

is, on my machine, more than twice as fast as your functions, e.g:

l = Table[If[Random[] < 0.0001, 1, 0], {10^6}];

FindLastNonzero[l]//Timing

{0.3 Second,989464}

FindLastNonzero1[l]//Timing

{0.12 Second,989464}

Andrzej Kozlowski
Chiba, Japan
http://www.mimuw.edu.pl/~akoz/

```

• Prev by Date: Re: Find last NZ in list
• Next by Date: Re: Find last NZ in list
• Previous by thread: Find last NZ in list
• Next by thread: Re: Find last NZ in list