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.

ClearAll["Global`*"] ;  lst = Prime[Range[6]] ;    MapIndexed[foo, lst]//TableForm

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.

MapIndexed[foo[#1, Sequence @@ #2] &, lst]//TableForm

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.

MapIndexed[{foo[#1], goo[#2]} &, lst]//TableForm

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}], ....

MapIndexed[{foo[#1], goo @@ #2} &, lst]//TableForm

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[foo, {{a, b}, {c, d}}, {2}]

{{foo[a, {1, 1}], foo[b, {1, 2}]}, {foo[c, {2, 1}], foo[d, {2, 2}]}}

MapIndexed[{foo[#1], goo[Sequence @@ #2]} &, {{a, b}, {c, d}}, {2}]

{{{foo[a], goo[1, 1]}, {foo[b], goo[1, 2]}}, {{foo[c], goo[2, 1]}, {foo[d], goo[2, 2]}}}

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}.

MapIndexed[foo, {a, b, c}, HeadsTrue]

foo[List, {0}][foo[a, {1}], foo[b, {2}], foo[c, {3}]]


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page