Re: <Null> while building lists

*To*: mathgroup at smc.vnet.net*Subject*: [mg112198] Re: <Null> while building lists*From*: Bill Rowe <readnews at sbcglobal.net>*Date*: Sat, 4 Sep 2010 04:01:18 -0400 (EDT)

On 9/3/10 at 6:09 AM, alexxx.magni at gmail.com (Alessandro) wrote: >Hi group, I'm sure I'll bang me on my head as soon as I will Press ><Post Message>, but it's since yesterday that I'm struggling with >this... >I fast defined this awkward function, to collect the {index,value} >of the maxima of a list of reals (a Fourier transform): >maxima[f_] := Block[{old = f[[1]], m = {}}, >For[i = 2, i < Length[f]/2, i++, >If[f[[i]] > old && f[[i + 1]] < f[[i]], >AppendTo[m, {i, f[[i]]}]]; >old = f[[i]] >] >m >] >Problem is, what I get is e.g. this: > >>maxima[f] {{14 Null, 10.8853 Null}, {21 Null, 3.34261 Null}, {28 >>Null, 1.47219 Null}} >I'm sure I do not have spaces anywhere (it happened something >similar due to this error, time ago), so what's wrong? For your code to work as intended, you need to terminate the For[...] portion with a semicolon. As written, the last thing your code evaluates is the output from For (which will be a Null) times the array you built m which is not what you want. As an aside, code that uses For and AppendTo like this is not fast in Mathematica. If the data list isn't too large, then this may not matter. But if you are using Fourier to compute the FFT of a large data set, this code is going to be painfully slow. Here is an example of something that will work much faster for large data sets In[1]:= data = 6 Cos[2 x] + 3 Cos[5 x] /. x -> Rescale[Range[256] // N, {1, 256}, {0, 2 Pi}]; In[2]:= Most@ ArrayRules@SparseArray[Chop[Abs@Fourier[data][[;; 128]], 10]] /. HoldPattern[{a_} -> b_] :> {a, b} Out[2]= {{3, 48.31196595883446}, {6, 23.95982793367838}} Note, this is an example. To generalize this approach, I would want to change the hard coded value 10 to something computed from the data or the FFT of the data.