MATLAB: How to create a multidimensional matrix from a cell array where the cell array sizes are not he same

MATLAB: How to create a multidimensional matrix from a cell array where the cell array sizes are not he same

cell arrays

I have a cell array C
C{1,1} = {[1 2 3]}
C{1,2} = {[12 21 3]}
C{1,3} = {[12 21 3], [43 45 66]}
C{1,4} = {[2 5 1], [1 65 3], [32 5 1], [2 5 1]}
C{2,1} = {[1 2 3], [11 6 43], [1 5 1], [4 56 1]}
C{2,2} = {[12 21 3]}
C{2,3} = {[43 45 66]}
C{2,4} = {[1 65 3], [32 5 1], [2 5 1]}
C{3,1} = {[4 56 1]}
C{3,2} = {[12 21 3], [23 5 2], [2 4 2]}
C{3,3} = {[1 4 2], [43 45 66]}
C{3,4} = {[37 45 6]}
As can be seen, the cells are of different dimension. Each element of a cell has values like [x y z]
Now I want to convert this to a multidimensional matrix of dimension 3*4*4(in the above example) with the missing entries in the matrix to be [0 0 0].
C_New(1,1,:) = [1 2 3; 0 0 0; 0 0 0; 0 0 0]
C_New(1,2,:) = [12 21 3; 0 0 0; 0 0 0; 0 0 0]
C_New(1,3,:) = [12 21 3; 43 45 66; 0 0 0; 0 0 0]
C_New(1,4,:) = [2 5 1; 1 65 3; 32 5 1; 2 5 1]
.
.
.
.
C_New(3,1,:) = [4 56 1; 0 0 0; 0 0 0; 0 0 0]
C_New(3,2,:) = [12 21 3; 23 5 2; 2 4 2; 0 0 0]
C_New(3,3,:) = [1 4 2; 43 45 66; 0 0 0; 0 0 0]
C_New(3,4,:) = [37 45 6; 0 0 0; 0 0 0; 0 0 0]
what is the best way to do this? I want to do this because having a matrix makes it easy for me to vectorize my operations and gain speed. My actual cell arrays are much bigger (900*3600).
Any help is appreciated! 🙂

Best Answer

  • EDIT
    n = cellfun(@numel,C);
    nmx = max(n(:));
    K = cellfun(@(x,y)[cat(1,x{:});zeros(nmx-y,3)],C,num2cell(n),'un',0);
    CC = cat(3,K{:});
    C_New = reshape(CC,[nmx,3,size(C)]);
  • Add a Comment

    Your email address will not be published. Required fields are marked *