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?
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.
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));
-
(+1) for a cleaner solution than mine... I know the
mat2cell
and its reversecell2mat
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...)– FlorisFeb 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
-
1Completely 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.– FlorisFeb 1, 2013 at 13:49
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.
num2cell( [1 2 3;4 5 6;7 8 9], 2)