Christina
Christina

Reputation: 935

Resizing a 3D matrix into a 2D matrix in MATLAB

I have the following three-dimensional matrix X of size 2*2*3:

X = zeros(2, 2, 3);
X(:,:,1) = [1 2; 3 4];
X(:,:,2) = [5 6; 7 8];
X(:,:,3) = [9 10; 11 12];

I want to automatically reshape X to a two-dimensional matrix of size 6*2 such that I should obtain:

X_reshaped = [1 2; 3 4; 5 6; 7 8; 9 10; 11 12].

In MATLAB, I am trying to write X_reshaped = reshape(X, [size(X,1)*size(X,3), size(X,2)]), but this doesn't give me the desired X_reshaped as above.

Any help will be very appreciated!

Upvotes: 2

Views: 773

Answers (1)

MichaelTr7
MichaelTr7

Reputation: 4757

Using the permute() function will allow the array to be reshaped so that the elements are stored in pairs along the first dimension. This allows the reshape() function to access those pairs accordingly by default.

X = zeros(2, 2, 3); 
X(:,:,1) = [1 2; 3 4];
X(:,:,2) = [5 6; 7 8];
X(:,:,3) = [9 10; 11 12];

reshape(permute(X,[1 3 2]),[6 2])

Upvotes: 3

Related Questions