Re: message 50001?
- To: mathgroup at smc.vnet.net
- Subject: [mg50045] Re: [mg50001] message 50001?
- From: "Dr A.H. Harker" <a.harker at ucl.ac.uk>
- Date: Thu, 12 Aug 2004 05:45:01 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
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 slower. 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 LONDON WC1E 6BT (44)(0)207 679 3404 a.harker at ucl.ac.uk ]->-----Original Message----- ]->From: 1.156 [mailto:rob at pio-vere.com] To: mathgroup at smc.vnet.net ]->Sent: 11 August 2004 10:53 ]->To: mathgroup at smc.vnet.net ]->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 of ]->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