Re: Value and position in list
- To: mathgroup at smc.vnet.net
- Subject: [mg33423] Re: Value and position in list
- From: Jens-Peer Kuska <kuska at informatik.uni-leipzig.de>
- Date: Thu, 21 Mar 2002 09:27:00 -0500 (EST)
- Organization: Universitaet Leipzig
- References: <a79ckp$7uk$1@smc.vnet.net>
- Reply-to: kuska at informatik.uni-leipzig.de
- Sender: owner-wri-mathgroup at wolfram.com
Hi, minpos = Compile[{{lst, _Real, 2}}, Module[{i = 1}, MapIndexed[If[First[#] < lst[[i, 1]], i = First[#2], 0] &, lst]; {{i, 1}} ] ] minpos[data] // Timing should be faster. Regards Jens Hugh Goyder wrote: > > I have a list where each element is a list of three values > {{v11,v12,v13},{v21,v22,v23}...}. > What is the fastest method for finding the position and value of the > element which has the smallest first element. > > I have the following but is it possible to do this more quickly, perhaps > without two sorts through the data? > > In[1]:= > $Version > > Out[1]= > 4.1 for Microsoft Windows (June 13, 2001) > > In[2]:= > data=Table[{Random[],Random[]-0.5,10(Random[]-0.5)},{10000}]; > > In[3]:= > Timing[a=Min[Transpose[data][[1]]];p=Position[data,a];{a,p}] > > Out[3]= > {0.33 Second,{0.0000316723,{{1706,1}}}} > > I must also find the element which has the smallest second element greater > than zero. Here are my attempts so far. Is there a faster method? > > In[4]:= > Timing[a=Infinity;i=0; > While[i++;i<Length[data],If[0<data[[i,2]]<a,a=data[[i,2]];p=i]];{a,p}] > > Out[4]= > {1.31 Second,{0.0000126855,1134}} > > In[5]:= > Timing[a=Min[Transpose[data][[2]]/.v_/;v\[LessEqual] 0 \[Rule] Infinity]; > p=Position[data,a];{a,p}] > > Out[5]= > {0.71 Second,{0.0000126855,{{1134,2}}}} > > In[6]:= > Timing[a=Min[Select[Transpose[data][[2]],#>0&]];p=Position[data,a];{a,p}] > > Out[6]= > {0.61 Second,{0.0000126855,{{1134,2}}}} > > Thank you for your ideas > > Hugh Goyder