MathGroup Archive 2004

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

Search the Archive

Re: message 50001?

Dear Rob,

          As ever, there's a balance to be struck between elegance and
efficiency. One can invent all sorts of fancy code that "hides" loops,
but in the end it's worth considering how many passes through the data
are required to obtain the result. Presumably Max makes one complete
pass through the array, and the For loop makes another, so the number of
operations scales like n, the number of entries in the list (when I say
"scales like", I mean it's proportional to n, not to some power of n).
Anything involving a new list with the entries and their original
positions, sorted, would scale like n log(n), so would probably be

  In a few trials (1000 trials each of 1000-long lists of random data:
the details change with different lengths, but I don't think the
orderings do), I found that
   For[i = 1, S[[i]] != Max[S], i++, x == len]
was very slow, and despite the rebuilding of the list and the full sort
   Sort[Transpose[{S, Range[Length[S]]}]][[-1, 2]]
was about twice as fast
   Position[S, Max[S]][[1, 1]]
cut the time by another factor of 5, but the out-and-out winner, at
least ten times as fast again, was
   Ordering[S, -1][[1]]
I can only assume that Ordering has special cases built into it to
handle a search for the maximum or minimum, as it rapidly slows if one
asks for the positions of items which would be further from the end of
the sorted list.

  When I started playing with this, I'd assumed, on the basis of my
first paragraph, that 
    Position[S, Max[S]][[1, 1]]
would be fastest. I was wrong!

 Tony Harker (Dr A.H. Harker)
 Director of Postgraduate Studies
 Deputy Head, Condensed Matter and Materials Physics Group
 Department of Physics and Astronomy
 University College London
 Gower Street
 WC1E  6BT
 (44)(0)207 679 3404
 a.harker at

]->-----Original Message-----
]->From: 1.156 [mailto:rob at]
To: mathgroup at
]->Sent: 11 August 2004 10:53
]->To: mathgroup at
]->Subject: [mg50045] [mg50001] message 50001?
]->Mathematica wizards, I've managed to cripple together code to do
]->something that
]->I feel must be doable more easily and/or faster.
]->S is a list of reals containing a signal with a prominent peak in
]->amplitude. I simply want to find the index of the peak (x, the number
]->entries into the list where the peak occurs). Here's what I did.
]->For[i = 1, S[[i]] ? max[S], i++, x = i];
]->Can some suggest a better way, especially one not using a For loop?
]->Thanks, Rob

  • Prev by Date: RE: how to graphically fill the tails of a normal distribution
  • Next by Date: Smalest enclosing circle
  • Previous by thread: Re: message 50001?
  • Next by thread: Nonlinearfit (real function with complex entries)