Hadi
Hadi

Reputation: 119

How can I insert each row of a matrix into cells in 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?

Upvotes: 3

Views: 6265

Answers (2)

HebeleHododo
HebeleHododo

Reputation: 3640

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));

Upvotes: 7

Floris
Floris

Reputation: 46375

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.

Upvotes: 1

Related Questions