0
$\begingroup$

I'm a beginner in Mathematica. I have the following code:

A = NestList[func, x0, n];
B = Partition[Flatten[{#, #, #, #} & /@ A][[2 ;; -2]], 2]

I don't understand the meaning of the syntax for B. What exactly is happening there (could someone explain this in words?). How could one understand the interval directly after the Flatten function and what is it addressing?

$\endgroup$
  • 2
    $\begingroup$ What about evaluating this step by step? {#, #, #, #} & /@ A then Flatten[%] etc? $\endgroup$ – Kuba Feb 14 '18 at 19:55
  • 1
    $\begingroup$ This is a Great tip. Tried it out and now i‘m wondering why i didn‘t do this in the first place ✌️ $\endgroup$ – JtSpKg Feb 15 '18 at 10:27
3
$\begingroup$

Let's look at it from the inside out, starting with

{#,#,#,#} &

This is a nameless function which takes any input and returns a list containing that input 4 times by directly repeating its argument.

{#,#,#,#} & /@ A

This Maps (/@ is a shorthand infix for Map) the nameless function over every member of A. This returns a list containing lists of 4 copies for every member of A.

Flatten[{#,#,#,#} & /@ A]

This flattens that list of lists back into a normal list, effectively creating a 1D list repeating each element of A 4 times in the same order that A has them.

Flatten[{#,#,#,#} & /@ A][[2 ;; -2]]

This then takes the second through second to last members of that list, discarding the very first and the very last elements.

Partition[Flatten[{#,#,#,#} & /@ A][[2 ;; -2]], 2]

Finally this breaks the list into non-overlapping pairs, starting from the beginning.

$\endgroup$
  • $\begingroup$ Thanks a lot for this clear explanation. In the Future i will try to decompose new confusing code similarly. $\endgroup$ – JtSpKg Feb 15 '18 at 10:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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