Services & Resources / Wolfram Forums / MathGroup Archive
-----

MathGroup Archive 2010

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

Search the Archive

Re: First nonzero in list

  • To: mathgroup at smc.vnet.net
  • Subject: [mg110873] Re: First nonzero in list
  • From: Ray Koopman <koopman at sfu.ca>
  • Date: Fri, 9 Jul 2010 07:04:00 -0400 (EDT)
  • References: <i13tq3$7gd$1@smc.vnet.net>

On Jul 8, 12:13 am, "S. B. Gray" <stev... at ROADRUNNER.COM> wrote:
> I have lists such as
>
> th = {227, 342, 527, 0, 670, 730, 703, 0, 0, 649, 687, 614, 570, 501,
>    462, 402, 325, 254, 189, 99, 81, 36, 9, 8, 3, 0, 0, 0, 0, 0, 0, 0,
>    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
>     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
>
> and I want to find the position of the last nonzero element (e.g. 3 at
> position 25). Trivial, but some poking around did not reveal a neat way.
>
> Anyone? Thank you.
>
> Steve Gray

This will do integer lists quite quickly,
and a similar function will do real lists.

In[2]:= InputForm[ poslastnzi = Compile[{{v, _Integer, 1}},
   Module[{i = Length[v]}, While[i > 0 && v[[i]] == 0, i--]; i]] ]

Out[2]//InputForm=
CompiledFunction[{{_Integer, 1}}, {{2, 1, 0}, {2, 0, 0}},
 {4, 4, 0, 0, 1}, {{1, 5}, {57, 0, 0}, {4, 0, 1},
  {48, 1, 0, 0}, {41, 0, 6}, {64, 0, 0, 0, 0, 1}, {4, 0, 2},
  {44, 1, 2, 1}, {8, 1, 3}, {42, 3}, {3, False, 2},
  {8, 2, 3}, {41, 3, 6}, {9, 0, 1}, {4, 1, 2},
  {89, 258, 2, 0, 1, 2, 0, 2, 2, 0, 3}, {9, 3, 0},
  {42, -15}, {2}}, Function[{v}, Module[{i = Length[v]},
   While[i > 0 && v[[i]] == 0, i--]; i]], Evaluate]

In[3]:= poslastnzi[th]

Out[3]= 25


  • Prev by Date: image is not graphics
  • Next by Date: Re: replacement x->y except in Exp[x]
  • Previous by thread: Re: First nonzero in list
  • Next by thread: FindMinimum numerical constraint functions