Andi
Andi

Reputation: 4855

MATLAB: Transform 3D into 2D (concatenation)

I need to transform a 3D array s into a 2D array sReshape in a way where every slice of the third dimension will simply be put below the rows of the first slice's 2D array.

Here's the example as well as the expected solution:

s = reshape((1:30),[5,3,2]);
sReshape = ???

resultExpected = [(1:5),(16:20) ; (6:10),(21:25) ; (11:15),(26:30)]';
isequal(sReshape, resultExpected)

Upvotes: 0

Views: 185

Answers (1)

user2999345
user2999345

Reputation: 4195

you can use permute to switch between the second and third dimensions before reshaping:

s = reshape((1:30),[5,3,2]);
% switch between the 2nd and third dimensions
y = permute(s,[1 3 2]);
% reshape into 3 columns matrix
sReshape = reshape(y,[],3);

resultExpected = [(1:5),(16:20) ; (6:10),(21:25) ; (11:15),(26:30)]';
isequal(sReshape, resultExpected)

Upvotes: 2

Related Questions