I have a list and an arbitrary function taking 4 parameters, let's say {1, 11, 3, 13, 9, 0, 12, 7}
and f[{x,y,z,w}]={x+y, z+w}
, what I want to do is to form a new list such that 4 consecutive elements in the original list are evaluated to get a new value as the new list's component, and the evaluation has to be done in every 2 positions in the original list, in this case, the resulting list is:
{{12, 16}, {16, 9}, {9, 19}}
Note here 4 and 2 can change. How to do this conveniently in Mathematica? I imagine this as something like Map
, but not sure how to relate.
Details. Flatten "unravels" lists, effectively just deleting inner braces. Flatten[list,n] effectively flattens the top level in list n times.
Module allows you to set up local variables with names that are local to the module. Module creates new symbols to represent each of its local variables every time it is called. Module creates a symbol with name xxx$nnn to represent a local variable with name xxx.
In the text-based interface, pressing Enter will work. If you are running Mathematica on a workstation with a graphical user interface, to start the program, either use the command mathematica & or click the Mathematica icon.
There's an alternative to Map[f, Partition[...]]
: Developer`PartitionMap
. Which works exactly like Map[f, Partition[list, n, ...]]
. So, your code would be
Needs["Developer`"]
f[{x_, y_, z_, w_}] = {x + y, z + w};
list = {1, 11, 3, 13, 9, 0, 12, 7};
PartitionMap[f,list, 4, 2]
giving the same result as Mark's answer.
f[{x_, y_, z_, w_}] = {x + y, z + w};
list = {1, 11, 3, 13, 9, 0, 12, 7};
f /@ Partition[list, 4, 2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With