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?

  • 1
    $\begingroup$ is defining f as Listable an option? $\endgroup$ Aug 27 '13 at 18:40
  • $\begingroup$ Yes. It is an option. $\endgroup$
    – dnet
    Aug 27 '13 at 18:44
  • 1
    $\begingroup$ 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) $\endgroup$
    – Nasser
    Aug 27 '13 at 19:00
  • $\begingroup$ @Nasser you're correct. Although I think Pinguin's Listable method is simpler than the solutions proposed on your question. $\endgroup$
    – rcollyer
    Aug 27 '13 at 19:07
  • $\begingroup$ @Nasser Thank you for pointing me to your question! $\endgroup$
    – dnet
    Aug 27 '13 at 19:12

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


and then simply:


to obtain:

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


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


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

  • $\begingroup$ Very nice. Thank you. $\endgroup$
    – dnet
    Aug 27 '13 at 18:46
  • $\begingroup$ What if f is just List? Is there a special solution for that case? $\endgroup$
    – dnet
    Aug 27 '13 at 18:51
  • 2
    $\begingroup$ @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. $\endgroup$
    – rcollyer
    Aug 27 '13 at 19:02
  • $\begingroup$ 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 :) $\endgroup$
    – Nasser
    Aug 27 '13 at 19:06
  • $\begingroup$ @Pinguin I would have given you +1, but I forgot. The update, though seals it. :) $\endgroup$
    – rcollyer
    Aug 27 '13 at 19:16

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

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


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.