RE: Find last NZ in list

• To: mathgroup at smc.vnet.net
• Subject: [mg46114] RE: [mg46102] Find last NZ in list
• From: "Florian Jaccard" <florian.jaccard at eiaj.ch>
• Date: Sat, 7 Feb 2004 04:01:57 -0500 (EST)
• Sender: owner-wri-mathgroup at wolfram.com

```Does this do it ?

findLastNonZero[liste_] :=
If[Position[(StringMatchQ[#1, "0"] & ) /@
ToString /@ liste, False] != {},
Last[Position[(StringMatchQ[#1, "0"] & ) /@
ToString /@ liste, False]][[1]], 0]

F.Jaccard

-----Message d'origine-----
De : Carlos Felippa [mailto:carlos at colorado.edu]
Envoyé : ven., 6. février 2004 10:15
À : mathgroup at smc.vnet.net
Objet : [mg46102] Find last NZ in list

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.

```

• Prev by Date: Re: Find last NZ in list
• Next by Date: What is ListConvolve doing here?
• Previous by thread: Re: Find last NZ in list
• Next by thread: Re: Find last NZ in list