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