Search code examples
matlabmatrixcell-array

How can I convert a cell to matrices by loop using with cell2mat in Matlab?


I have a cell A(361,1) which contains 361 x 3D matrices. The first and second dimensions of matrices are same but the length of third dimension varies.

So the cell A looks like:

A={(464x201x31);(464x201x28);(464x201x31);(464x201x30)....}

I would like to get back the matrices from this cell by loop. I tried the following solution:

for i=1:361;
M(i)=cell2mat(A(i));
end 

But I got the following error:

Subscripted assignment dimension mismatch.


Solution

  • 1. If you want to access each 3D array separately from the cell array, you could always use A{i} to get each 3D matrix.

    Example:

    %// Here i have taken example cell array of 1D matrix 
    %// but it holds good for any dimensions
    
    A = {[1,2,3], [1,2,3,4,5], [1,2,3,4,5,6]};
    
    >> A{1}
    
    ans =
    
     1     2     3
    

    2. Instead, if you want to concatenate all those 3D matrices into a single three dimensional matrix, here is one approach

    out = cell2mat(permute(A,[1 3 2]));  %// assuming A is 1x361 from your example
    

    or

    out = cell2mat(permute(A,[3 2 1]));  %// assuming A is 361x1 
    

    3. Instead if you wanna NaN pad them to obtain 4D matrix,

    maxSize = max(cellfun(@(x) size(x,3),A));   
    f = @(x) cat(3, x, nan(size(x,1),size(x,2),maxSize-size(x,3)));  
    out = cellfun(f,A,'UniformOutput',false); 
    out = cat(4,out{:}); 
    

    Sample run:

    >> A
    
    A = 
    
    [3x4x2 double]    [3x4x3 double]    [3x4x4 double]
    
    >> size(out)
    
    ans =
    
     3     4     4     3 
    %// note the first 3 size. It took the max size of the 3D matrices. i.e 3x4x4
    %// Size of 4th dimension is equal to the no. of 3D matrices   
    

    You could access each 3D matrix by out(:,:,:,i)