Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement such a map-like operation in mathematica

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.

like image 317
Qiang Li Avatar asked Jan 08 '12 01:01

Qiang Li


People also ask

What is flatten in Mathematica?

Details. Flatten "unravels" lists, effectively just deleting inner braces. Flatten[list,n] effectively flattens the top level in list n times.

What is module in Mathematica?

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.

How do you go to the next line in Mathematica?

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.


2 Answers

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.

like image 75
rcollyer Avatar answered Oct 14 '22 15:10

rcollyer


f[{x_, y_, z_, w_}] = {x + y, z + w};
list = {1, 11, 3, 13, 9, 0, 12, 7};
f /@ Partition[list, 4, 2]
like image 21
Mark McClure Avatar answered Oct 14 '22 14:10

Mark McClure