MapThread


MapThread can be used to Apply a function to each column of a matrix as I do
in the next cell. However, before using MapThread I clear the values from all
variables.

ClearAll["Global`*"] ;  mat = {{a, b, c, d, e, f}, {1, 2, 3, 4, 5, 6}} ;    MapThread[foo, mat]

{foo[a, 1], foo[b, 2], foo[c, 3], foo[d, 4], foo[e, 5], foo[f, 6]}


MapThread is equivalent to using Map followed by Apply at level 2 (see
below).  I have to wonder why it isn't called ApplyThread.

MapThread[foo, mat] === Apply[foo, Thread[mat], 2]

True


In the next few lined we use MapThread to work with the tensor below.

Off[General :: spell1]    tensor = {           ... , a324}}       } ;    On[General :: spell1]    Dimensions[tensor]

{3, 2, 4}

In the next line MapThread is used on the above tensor.

t1 = MapThread[foo, tensor] ;    t1[[1]]

foo[{a111, a112, a113, a114}, {a211, a212, a213, a214}, {a311, a321, a323, a324}]

t1[[2]]

foo[{a121, a122, a123, a124}, {a221, a222, a223, a224}, {a321, a322, a323, a324}]


MapThread can work on the tensor above with a third argument as in the next
example, and gives a very different result than the previous example.

t2 = MapThread[foo, tensor, 2] ;    t2[[1]]

{foo[a111, a211, a311], foo[a112, a212, a321], foo[a113, a213, a323], foo[a114, a214, a324]}

t2[[2]]

{foo[a121, a221, a321], foo[a122, a222, a322], foo[a123, a223, a323], foo[a124, a224, a324]}

An interesting application of MapThread is given below where MapThread is  used to apply a list of functions to a list of arguments.  The #& notation is  explained in the discussion of Function.

funcs = {f1, f2, f3} ;    values = {val1, val2, val3} ;    MapThread[(#1[#2]) &, {funcs, values}]

{f1[val1], f2[val2], f3[val3]}


Alan Hayes provided the code below to make a list of replacement rules.

pos = Array[p, {4, 3}]

{{p[1, 1], p[1, 2], p[1, 3]}, {p[2, 1], p[2, 2], p[2, 3]}, {p[3, 1], p[3, 2], p[3, 3]}, {p[4, 1], p[4, 2], p[4, 3]}}

posval = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {11, 12, 13}} ;    Flatten[MapThread[Rule, {pos, posval}, 2]]

{p[1, 1] 1, p[1, 2] 2, p[1, 3] 3, p[2, 1] 4, p[2, 2] 5 ...  p[3, 2] 8, p[3, 3] 9, p[4, 1] 11, p[4, 2] 12, p[4, 3] 13}


Created by Mathematica  (May 16, 2004)

Back to Ted’s Tricks index page