Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1997
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1997

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

Search the Archive

Re: selecting from lists

  • To: mathgroup at smc.vnet.net
  • Subject: [mg6165] Re: [mg6120] selecting from lists
  • From: gaylord at ux1.cso.uiuc.edu (richard j. gaylord)
  • Date: Thu, 27 Feb 1997 02:52:05 -0500
  • Organization: university of illinois
  • Sender: owner-wri-mathgroup at wolfram.com

In article <5em0qi$3ln at smc.vnet.net>, murray at math.umass.edu (Murray
Eisenberg) wrote:

> Actually, the general problem as I formulated it above is just the tip
> of the iceberg of things that are giving me trouble in Mathematica
> that are so easy for me in APL or J.  For example, construct a
> function firstnonzero that returns the index of the first nonzero
> entry in a list (or, more generally, the first entry in a list
> satisfying a given property).  Here the best I've come up with that
> avoids explicit looping is:
> 
>    nonzero[x_] != 0; SetAttributes[nonzero, Listable]
>    firstnonzero[v_] := First[s[Range[Length[v]], nonzero[v]]]
> 
> In these and similar problems, I have the feeling that there ought to
> be some slick approach using patterns, but I don't see how to do it.


hi murray:

you've got to break this APL/J hangup. there is almost nothing that can be
done in J or APL that can't be done as elegantly [and alot more
understandably in mathematica].

assuming index means location?

In[58]:=
lis = Table[Random[Integer], {10}]
Out[58]=
{0, 0, 1, 1, 0, 1, 0, 0, 0, 1}

In[59]:=
Position[lis, _?Positive | _?Negative, 1,  1]
Out[59]=
{{3}}


and if you want, you can 

In[64] =
Position[lis, _?Positive | _?Negative, 1,  1]
Out[64]=
{3}


or

In[65]:=
Position[lis, _?Positive | _?Negative, 1,  1][[1, 1]]
Out[65]=
3


not to mention, the ever popular

In[67]:=
Position[lis, First[DeleteCases[lis, 0]], 1, 1]
Out[67]=
{{3}}

note: i have not done any speedtests  on these ways. there are other ways
as well.


 
> Any help in putting me onto the right track in "Mathematica thinking"
> about such problems would be appreciated.

modesty prevents me from suggesting that you read chapters 3 and 4, in the
Introduction to Programming with Mathematica" book.  :)

-richard-

-- 
richard j. gaylord, university of illinois, gaylord at uiuc.edu

"human decisions, whether personal or political or economic, cannot depend upon ....  mathematics, since the bases for making such calculations do not exist"
- John Maynard Keynes -


  • Prev by Date: printing and font problems
  • Next by Date: AxesLabel puts "Null" on graph axis!
  • Previous by thread: Re: selecting from lists
  • Next by thread: Re: selecting from lists