Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a cell array of 2D matrices into a multidimensional array in MATLAB

In MATLAB, I have a defined cell array C of

size(C) = 1 by 150

Each matrix T of this cell C is of size

size(C{i}) = 8 by 16

I am wondering if there is a way to define a new multidimension (3D) matrix M that is of size 8 by 16 by 150

That is when I write the command size(M) I get 8 by 16 by 150

Thank you! Looking forward for your answers

like image 698
Henry Avatar asked Dec 03 '25 09:12

Henry


1 Answers

If I'm understanding your problem correctly, you have a cell array of 150 cells, and each cell element is 8 x 16, and you wish to stack all of these matrices together in the third dimension so you have a 3D matrix of size 8 x 16 x 150.

It's a simple as:

M = cat(3, C{:});

This syntax may look strange, but it's very valid. The command cat performs concatenation of matrices where the first parameter is the dimension you want to concatenate to... so in your case, that's the third dimension, and the parameters after are the matrices you want to concatenate to make the final matrix.

Doing C{:} creates what is known as a comma-separated list. This is equivalent to typing out the following syntax in MATLAB:

C{1}, C{2}, C{3}, ..., C{150}

Therefore, by doing cat(3, C{:});, what you're really doing is:

cat(3, C{1}, C{2}, C{3}, ..., C{150});

As such, you're taking all of the 150 cells and concatenating them all together in the third dimension. However, instead of having to type out 150 individual cell entries, that is encapsulated by creating a comma-separated list via C{:}.

like image 80
rayryeng Avatar answered Dec 04 '25 23:12

rayryeng