Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2004
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*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 smc.vnet.net
  • Subject: [mg46115] Re: Find last NZ in list
  • From: "Bo Le" <bole79 at email.si>
  • Date: Sat, 7 Feb 2004 04:01:58 -0500 (EST)
  • References: <bvvnir$j5k$1@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Hi,

Your words are not very clear on what you want, either the last nonzero element or its
index, but from the examples you provide I guess it is the index.

I came up with a nice solution for the element and somewhat the same (fancied up)
construct to yours for the index:


FindLastNonzeroElement[lst_]:=
  Module[{tmp=DeleteCases[lst,0]},
    If[Length[tmp]!=0,Last[tmp],0]
    ]


FindLastIndex[lst_]:=
  Catch[
    For[i=Length[lst],i>=0,i--,
      If[lst[[i]]!=0,Throw[i]];
      If[i==0,Throw[0]];
      ]
    ]


Bye!

Borut Levart
Slovenia


"Carlos Felippa" <carlos at colorado.edu> wrote in message news:bvvnir$j5k$1 at smc.vnet.net...
> 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: Re: random numbers?
  • Previous by thread: Re: Find last NZ in list
  • Next by thread: Re: Find last NZ in list