# How to elegantly map multiple functions over a matrix?

plus     = Map[Plus[#[[1]], #[[2]]] &,     Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}];
subtract = Map[Subtract[#[[1]], #[[2]]] &, Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}];
times    = Map[Times[#[[1]], #[[2]]] &,    Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}];
divide   = Map[Divide[#[[1]], #[[2]]] &,   Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}];
ops = {plus, subtract, times, divide};


The first four statements differ only by the functions they perform. Therefore, I want to combine them together for a better reusability.

How can I compactly combine the five statements into a single one, something like

  ops = ({plus, subtract, times, divide} = (possibly some code here...), Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}] (possibly some code here);?

• Look into Through... but there are other means vs mapping that are "prettier" to get your results
– ciao
Jun 21, 2015 at 9:01
• @ciao Thanks. How should I combine Through with Map and Table? My trials produce strange results. Jun 21, 2015 at 9:12

You very nearly had it. What you need, instead of Map[], is Apply[]. This can then be combined with Map[], like so:

mat = Table[{i, j}, {i, 2}, {j, 2}];
Apply[#, mat, {2}] & /@ {Plus, Subtract, Times, Divide}

• (This Mathematica Gedanken Version is quite taxing to use!) Jun 21, 2015 at 9:23
• I wonder what do you do when the garbage collector starts swinging Jun 21, 2015 at 9:27
• Why, I step out and hand him my filled-up trash bag, of course. Jun 21, 2015 at 9:32

This is really a natural fit for Outer:

t = Table[{i, j}, {i, 1, 2}, {j, 1, 2}];

Outer[Apply, {Plus, Subtract, Times, Divide}, t, 2]

(*
==> {{{2, 3}, {3, 4}}, {{0, -1}, {1, 0}}, {{1, 2}, {2, 4}}, {{1, 1/2}, {2, 1}}}
*)

• +1. Great to be reminded for what use case Outer was conceived of.
– gwr
Jun 21, 2015 at 17:10
• @gwr Thanks - I guess one can recognize that Outer is tailored for this scenario, from the fact that no # and & appears in this code...
– Jens
Jun 21, 2015 at 19:30

You might just map the Maps

ops = {plus, subtract, times, divide} =
Function[op, Map[op[#[[1]], #[[2]]] &, Table[{i, j}, {i, 1, 2}, {j, 1, 2}], {2}]] /@
{Plus, Subtract, Times, Divide}

{{{2, 3}, {3, 4}}, {{0, -1}, {1, 0}}, {{1, 2}, {2, 4}}, {{1, 1/2}, {2, 1}}}


If Table is part of your actual operation you will be served by learning Array:

Array[#, {2, 2}] & /@ {Plus, Subtract, Times, Divide}

{
{{2, 3}, {3, 4}},
{{0, -1}, {1, 0}},
{{1, 2}, {2, 4}},
{{1, 1/2}, {2, 1}}
}


An alternative using Replace to do this:

mytable = Table[{i, j}, {i, 1, 2}, {j, 1, 2}];
Replace[mytable, List[a_, b_] -> #[a, b], {-2}] & /@ {Plus, Subtract, Times, Divide}


{{{2, 3}, {3, 4}}, {{0, -1}, {1, 0}}, {{1, 2}, {2, 4}}, {{1, 1/2}, {2, 1}}}