Tak
Tak

Reputation: 3616

Combine 2D matrices to form 3D one in Matlab

I have 3 20x2 double arrays A, B and C. I want to combine them in one 3d array D so that D(:,:,1) will return A, D(:,:,2) will return B and D(:,:,3) will return C.

Upvotes: 3

Views: 3721

Answers (2)

Divakar
Divakar

Reputation: 221514

Using cat to concatenate along the third dimension might be the elegant way -

D = cat(3,A,B,C)

Here, the first input argument 3 specifies the dimension along which the concatenation is to be performed.

Upvotes: 5

Potaito
Potaito

Reputation: 1190

Like this?

A = 1*ones(20,2);
B = 2*ones(20,2);
C = 3*ones(20,2);

D = zeros(20,2,3);  % Preallocate the D Matrix
D(:,:,1) = A;       
D(:,:,2) = B;
D(:,:,3) = C;

D(1,1,1)  % prints 1
D(1,1,2)  % prints 2
D(1,1,3)  % prints 3

Upvotes: 1

Related Questions