Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert each row of a matrix into cells in Matlab?

Tags:

cell

matlab

Suppose A = [1 2 3;4 5 6;7 8 9] I want to convert it to B = [{[1,2,3]};{[4,5,6]};{[7,8,9]}] How can I do that in an easy way?

like image 218
Hadi Avatar asked Dec 21 '25 09:12

Hadi


2 Answers

You can use mat2cell function.

From the documentation:

C = mat2cell(A,dim1Dist,...,dimNDist) divides array A into smaller arrays within cell array C. Vectors dim1Dist,...dimNDist specify how to divide the rows, columns, and (when applicable) higher dimensions of A.

mat2cell

You can do it like this:

A = [1 2 3; 4 5 6; 7 8 9];
B = mat2cell(A, [1 1 1], 3);

will give you:

B={[1 2 3];[4 5 6];[7 8 9]}

Documentation also says:

C = mat2cell(A,rowDist) divides array A into an n-by-1 cell array C, where n == numel(rowDist).

So, if you are always going to split your matrix to rows, but not to columns, you can do it without the second parameter.

B = mat2cell(A, [1 1 1]);

A better, generalized way would be:

mat2cell(A, ones(1, size(A, 1)), size(A, 2));
like image 75
HebeleHododo Avatar answered Dec 22 '25 22:12

HebeleHododo


You can't have a "matrix of cells" like your notation for B implied. A cell array allows you to store "any data type" in the individual cells. You can't store a cell as a data type in an array.

So let's assume you meant to say you wanted B = {[1,2,3], [4,5,6], [7,8,9]};

If that is the case, then

B = cell(1,3);
for ii=1:3
  B(ii) = {A(ii, :)};
end

should do the trick.

Note - edited based on Hadi's comment.

like image 36
Floris Avatar answered Dec 22 '25 21:12

Floris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!