Search code examples
matlabcell

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?


Solution

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