# How to combine elements of two matrices?

Given two matrices m1 and m2, e.g.:

m1 = {{a1, b1}, {c1, d1}}
m2 = {{a2, b2}, {c2, d2}}


How can one obtain the following?

{{f[a1, a2], f[b1, b2]}, {f[c1, c2], f[d1 ,d2]}}


I found this solution

MapThread[f, {m1, m2}, 2]


Is there a simpler way?

-
is defining f as Listable an option? –  Pinguin Dirk Aug 27 '13 at 18:40
Yes. It is an option. –  dnet Aug 27 '13 at 18:44
This is an exact copy of a question I asked here mathematica.stackexchange.com/questions/29856/… where the example I had there had 3 matrices, and you have 2 matrices. So you can use the same exact answers there (there are total of 8 ways shown all together there) –  Nasser Aug 27 '13 at 19:00
@Nasser you're correct. Although I think Pinguin's Listable method is simpler than the solutions proposed on your question. –  rcollyer Aug 27 '13 at 19:07
@Nasser Thank you for pointing me to your question! –  dnet Aug 27 '13 at 19:12

Based on the comments, Listable is a possible way for you. Thus, you could:

SetAttributes[f,Listable]


and then simply:

f[m1,m2]


to obtain:

{{f[a1, a2], f[b1, b2]}, {f[c1, c2], f[d1, d2]}}

EDIT

To apply this on a built-in (non-Listable function) like List on could do, as noted by @rcollyer below:

f[m1,m2]/.f->List


(please also note his comment with regard to Block!)

Pure function approach

I also propose the following idea, which saves us from the trouble of making the keyfunction Listable:

Function[{x, y}, anyFunction[x, y], Listable][m1, m2]


The idea is to use a pure function that is Listable, thus we do not have to modify anyFunction. This works with List (instead of anyFunction) etc. as well.

-
Very nice. Thank you. –  dnet Aug 27 '13 at 18:46
What if f is just List? Is there a special solution for that case? –  dnet Aug 27 '13 at 18:51
@dnet f[m1, m2] /. f -> List. I would wrap the whole thing in Block, though: e.g. Block[{f}, SetAttributes[f,Listable]; f[m1, m2] /. f -> List], as this eliminates unintentional interactions with the rest of your code. –  rcollyer Aug 27 '13 at 19:02
You should add this nice answer to my question mathematica.stackexchange.com/questions/29856/… also. No one thought about it this way. Would have accepted this one if I saw it there :) –  Nasser Aug 27 '13 at 19:06
@Pinguin I would have given you +1, but I forgot. The update, though seals it. :) –  rcollyer Aug 27 '13 at 19:16

Perhaps not in spirit and purely for this configuration (i.e. not general enough)

f@@@ # & /@ {m1, m2}

-