Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have a list(kicks), and a function(fix). I am aware of the problem using Loop and Append or AppendTo. My question is why does the Flatten produce the desired output.

List:

kicks = {6.28992, 1.78953, 4.67832, 3.85717, 4.15561, 7.9862, 8.02365,
         2.62077, 5.89348, 6.50246}

Function:

 fix[list_] := Module[{xos, comp, ct},
    comp = {};
    xos = If[list > 7, AppendTo[comp, list]];
    ct = Flatten[comp]]

fix[#] & /@ kicks


Output: {{}, {}, {}, {}, {}, {7.9862}, {8.02365}, {}, {}, {}}

Desired output:

{7.9862, 8.02365}

I want to understand why Flatten in this case does not work, and how to solve it while using Module.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

You are applying Flatten inside the function that you map. Your flattened lists will still have the head List, and will produce the output you show. Instead you must either:

  • Flatten outside the function after mapping
  • Use Sequence as the head of the returned expression so that these are effectively flattened automatically.

The first is simply:

fix /@ kicks // Flatten
{7.9862, 8.02365}

The second would be something like:

fix2[list_] :=
 Module[{comp},
  comp = {};
  If[list > 7, comp = {comp, list}];
  Sequence @@ Flatten[comp]
 ]

fix2 /@ kicks
{7.9862, 8.02365}

However, using this function outside of Map may cause strange results as Sequence is returned to the top level (and may be caught by things like $PrePrint on the way).

Notes:

  • You do not need to embed fix in a new Function before mapping it: simply write fix /@ kicks
  • I presume that being aware of the problem with AppendTo you wanted a linked-lists format, so I included that in my fix2 example.
share|improve this answer
    
Sequence thats what I was looking for! Great thank you! –  ALEXANDER Sep 25 '13 at 20:56
    
@ALEXANDER You're welcome. –  Mr.Wizard Sep 25 '13 at 20:58
    
The "AppendTo problem" is AppendTo copies the list to generate the answer, right? –  Hector Sep 26 '13 at 1:01
1  
@Hector every time you change the length of a list you cause the underlying (low level) array to be reallocated, therefore append operations take time proportional to the length of the list. You can therefore make fast appends by using the format list = {list, new} or list = {new, list}, and then flattening at the end. Also see Sow and Reap, and Internal`Bag and related functions (search). –  Mr.Wizard Sep 26 '13 at 5:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.