ibezito
ibezito

Reputation: 5822

MATLAB - concatenation of 3rd matrix dimension

I have a 3D matrix of size KxNxZ. I would like to concatenate the sub matrices in the 3rd dimension into a single 2D matrix of size K*ZxN, s.t. they will be concatenated by rows. What's the best way to achieve this result?

Thanks!

Example:

%generates input
M = cat(3,[(1:3)',(4:6)'],[(7:9)',(10:12)'],[(13:15)',(16:18)']);
DesiredOutput = [[(1:3)';(7:9)';(13:15)'],[(4:6)';(10:12)';(16:18)']];

Input matrix

M(:,:,1) =
 1     4
 2     5
 3     6

M(:,:,2) =
 7    10
 8    11
 9    12

M(:,:,3) =
13    16
14    17
15    18

Desired output matrix:

DesiredOutput =

 1     4
 2     5
 3     6
 7    10
 8    11
 9    12
13    16
14    17
15    18

Upvotes: 2

Views: 362

Answers (1)

rayryeng
rayryeng

Reputation: 104555

Eskapp is on the right track. First use permute to swap the second and third dimensions so that you get a K x Z x N matrix. Once you do that, you can use reshape to unroll the matrix so that you take each 2D slice of size K x Z and transform this into a single one column with each column of the 2D slice becoming unrolled. Thankfully, this is how MATLAB works when reshaping matrices so naturally this will take very little effort. You'd then concatenate all of these columns together to make your matrix.

You first use permute this way:

Mp = permute(M, [1 3 2]);

This tells us that you want to swap the second and third dimension. Next, use reshape on this matrix so that you ensure that each column has K x Z elements where each column of a 2D slice is unrolled into a single column.

DesiredOutput = reshape(Mp, [], size(M,2));

size(M,2) accesses the value of N in the original matrix. You thus want to make DesiredOutputhave K*Z rows and N columns. Doing [] automatically infers how many rows we have for the output matrix to make things easy.

We thus get:

>> DesiredOutput

DesiredOutput =

     1     4
     2     5
     3     6
     7    10
     8    11
     9    12
    13    16
    14    17
    15    18

We can combine everything into one statement as the following if you don't want to use a temporary variable.

DesiredOutput = reshape(permute(M, [1 3 2]), [], size(M,2));

I primarily used a temporary variable to explain each step in the process.

Upvotes: 4

Related Questions