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$

1 Answer 1

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$
2
  • $\begingroup$ This is exactly what I was looking for. Thanks! $\endgroup$
    – ra91
    Mar 20, 2016 at 6:40
  • 3
    $\begingroup$ The Flatten[] version: Flatten[(* arrays *), {{2}, {3}, {1}}] $\endgroup$ Mar 20, 2016 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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