4
$\begingroup$

I have 3 nxn matrices that I'd like to combine into a nxnx3 tensor. Basically, I want a new nxn matrix where each element is a 3 tuple of the elements of the other 3 matrices at that same position. What would be the best way of doing this in mathematica?

$\endgroup$
3
$\begingroup$

Here is an example for n=3, using Transpose:

With[{n = 3}, 
 Transpose[{Array[a, {n, n}], Array[b, {n, n}], Array[c, {n, n}]}, {3, 1, 2}]]

(*
==> {{{a[1, 1], b[1, 1], c[1, 1]}, {a[1, 2], b[1, 2], 
   c[1, 2]}, {a[1, 3], b[1, 3], c[1, 3]}}, {{a[2, 1], b[2, 1], 
   c[2, 1]}, {a[2, 2], b[2, 2], c[2, 2]}, {a[2, 3], b[2, 3], 
   c[2, 3]}}, {{a[3, 1], b[3, 1], c[3, 1]}, {a[3, 2], b[3, 2], 
   c[3, 2]}, {a[3, 3], b[3, 3], c[3, 3]}}}
*)
$\endgroup$
  • $\begingroup$ This is exactly what I was looking for. Thanks! $\endgroup$ – ra91 Mar 20 '16 at 6:40
  • 3
    $\begingroup$ The Flatten[] version: Flatten[(* arrays *), {{2}, {3}, {1}}] $\endgroup$ – J. M. will be back soon Mar 20 '16 at 8:48

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.