lettura simple

Converting a Matrix into a Cell Array in Matlab

If you're working with matrices in Matlab and you want to convert them into cell arrays, there's a nifty little function called num2cell() that can do the trick for you.

num2cell(M)

It takes in a matrix or vector (M) as an argument and produces an output cell array with the same data as the matrix.

Where M is a matrix or a vector (array).

Note. Now, some folks might tell you to use mat2cell() instead, but I find that the result isn't quite the same.

Let me illustrate this for you with a practical example.

Suppose you have a 2x3 matrix with two rows and three columns. You can create this matrix in Matlab by typing:

>> M=[1 2; 3 4; 5 6]
M =

1 2
3 4
5 6

And then, to convert this matrix into a cell array, you simply type num2cell(M)

>> A=num2cell(M)
A =
{
[1,1] = 1
[2,1] = 3
[3,1] = 5
[1,2] = 2
[2,2] = 4
[3,2] = 6
}

This will give you a cell array with the same data as the matrix, where each cell contains a single data point.

Alternatively, you can use the mat2cell() function and specify the number of rows and columns of the matrix.

For example, type mat2cell(M,3,2)

>> C=mat2cell(M,3,2)
C =
{
[1,1] =
1 2
3 4
5 6
}

This will also generate a cell array, but the entire matrix will be stored in a single cell.

So there you have it, a quick and easy way to convert matrices into cell arrays in Matlab using the num2cell() function.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin