3

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?

1
  • 2
    try num2cell( [1 2 3;4 5 6;7 8 9], 2)
    – brown.2179
    Oct 18, 2015 at 22:25

2 Answers 2

7

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));
3
  • (+1) for a cleaner solution than mine... I know the mat2cell and its reverse cell2mat functions, but find that I always need the documentation to get them right. On a simple problem like the above, "quick and dirty" beats "clean, elegant, and slow" (because of the lookup in docs...)
    – Floris
    Feb 1, 2013 at 13:33
  • @Floris yes, quick and dirty is good if your matrix is 3x3, but if you are going for bigger datasets it is preferable to go for vectorized solutions. Feb 1, 2013 at 13:44
  • 1
    Completely agree @HebeleHododo - that is why I upvoted your solution. But I answered the question as it was asked... I am glad to see your answer has now been accepted as the correct one.
    – Floris
    Feb 1, 2013 at 13:49
1

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.

2
  • Thanks, both B = [{[1,2,3]};{[4,5,6]};{[7,8,9]}] and B = {[1,2,3], [4,5,6], [7,8,9]} have the same result but the latter is better show.
    – Hadi
    Feb 1, 2013 at 13:27
  • conversion from double to cell is needed. A(ii, :) must be inside braces like this: B(ii) = {A(ii, :)};
    – Hadi
    Feb 1, 2013 at 13:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.