normal

Converting a matrix into a cell array in Octave

In this lesson, I will explain how to convert a matrix into a cell array in Octave using the num2cell() function.

num2cell(M)

The parameter M can be either a matrix or a vector (array).

The function outputs an array of cells with the same data.

Note. You can also use the function mat2cell(M,r,c). However, in this case, you must also specify the number of rows and columns. The final result is not the same.

Let me give you a practical example.

Create a 2x3 matrix.

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

1 2
3 4
5 6

Type num2cell(M) to convert the matrix into an array of cells.

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

The function creates a 2x3 cell array with the same data as the matrix.

Alternatively, you can use the function mat2cell(M,r,c), where r and c are the number of rows and columns.

Type mat2cell(M,3,2)

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

In this specific scenario, the array is contained within a single cell.




Report a mistake or post a question




FacebookTwitterLinkedinLinkedin