MapIndexed
It's a little difficult to learn how to use the MapIndexed function. In the
next cell I clear values form all variables and give the simplest use of
MapIndexed. Notice the results are in the form f[2,{1}], f[3,{2}], etc.
foo[2, {1}] |
foo[3, {2}] |
foo[5, {3}] |
foo[7, {4}] |
foo[11, {5}] |
foo[13, {6}] |
Instead of the form above, one might rather have the result of MapIndexed in the form
f[2,1], f[3,2], etc. In the line above (f) is applied to two arguments, and the second argument has the head List. A result in the form f[2,1], f[3,2] is obtained in the next line by removing the head list from the second argument. Technically the head was changed to Sequence, then Sequence was removed during evaluation. The #& notation is explained in the discussion of Function.
foo[2, 1] |
foo[3, 2] |
foo[5, 3] |
foo[7, 4] |
foo[11, 5] |
foo[13, 6] |
Another use of MapIndexed involves mapping two functions as in the line
below.
foo[2] | goo[{1}] |
foo[3] | goo[{2}] |
foo[5] | goo[{3}] |
foo[7] | goo[{4}] |
foo[11] | goo[{5}] |
foo[13] | goo[{6}] |
In the next line (g@@#2) is used to ensure we end up with g[1], g[2], ..
instead of g[{1}], g[{2}], ....
foo[2] | goo[1] |
foo[3] | goo[2] |
foo[5] | goo[3] |
foo[7] | goo[4] |
foo[11] | goo[5] |
foo[13] | goo[6] |
By giving MapIndexed a level specification for only level 2 you can MapIndex to each element of a matrix.
MapIndexed can take a level specification using the same conventions as the examples where level specification is explained. A practical example that uses MapIndexed with a level specification is given in the section on Coefficient and CoefficientList.
Heads Option
MapIndexed has a Heads option with the default setting (Heads→False).
In the next cell we use (Heads→True) and the function with an index is
mapped to the head of {a,b,c}.
Created by Mathematica (May 16, 2004)