Services & Resources / Wolfram Forums
MathGroup Archive
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 2004

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

Search the Archive

Re: Find last NZ in list

  • To: mathgroup at
  • Subject: [mg46113] Re: Find last NZ in list
  • From: Mark Fisher <mefisher_news at>
  • Date: Sat, 7 Feb 2004 04:01:56 -0500 (EST)
  • References: <bvvnir$j5k$>
  • Sender: owner-wri-mathgroup at

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.

How about this?

FLN[data_ /; Union[data] == {0}] := 0
FLN[data_] := (Length[data] + 1) -
   Position[Reverse[data], _?(# =!= 0 &),
     {1}, 1, Heads -> False][[1, 1]]

The first definition applies if all the elements are zero. Otherwize, 
the second definition reverses the data and stops when the first nonzero 
match is found.

  • Prev by Date: Re: Specifying arguments inside nested functions
  • Next by Date: RE: Find last NZ in list
  • Previous by thread: Re: Plotting a 7 vertex graph in which every vertex has degree 4
  • Next by thread: RE: Find last NZ in list