Search code examples
arraysmatlabdoublecellreshape

Converting 2D cell of 2D matrices (consistent sizes) into 4D matlab double


Searching around here one finds many questions how one can convert cell arrays of doubles into one big matrix.
In my application I have a two dimensional cell array (lets call it celldata of size m times n) of all same sized double matrices (lets say of size a times b).
I want to convert that data structure into one bit 4D double (m times n times a times b).
At the moment I do that by

reshape(cat(3,celldata{:}),m,n,a,b)

but maybe there are other methods doing that directly? Maybe with a call like

cat([3 4],celldata{:,:})

or similar.


Solution

  • I think

    cell2mat(permute(celldata, [3 4 1 2]))
    

    will do the trick. However,

    %// create some bogus data
    m = 1.1e2;
    n = 1.2e2;
    
    a = 1.3e2; 
    b = 1.4e2;
    
    celldata = cellfun(@(~) randi(10, a,b, 'uint8'), cell(m,n), 'UniformOutput', false);
    
    %// new method
    tic
    cell2mat(permute(celldata, [3 4 1 2]));
    toc
    
    %// your current method
    tic
    reshape(cat(3,celldata{:}),m,n,a,b);
    toc
    

    Results:

    Elapsed time is 1.745495 seconds.  % cell2mat/permute
    Elapsed time is 0.305368 seconds.  % reshape/cat
    

    cell2mat is a matlab m-file (with necessary inefficiencies in the loop due to compatibility issues), while reshape and cat are built-ins. This is where that difference comes from.

    I'd stick with your current method :)

    Now, I'm asking you why you'd want to do this convesion in the first place. Is it an indexing problem? Because

    celldata{x,y}(w,z)  
    

    prevents you from having to do the conversion, so you can index like

    converted_celldata(x,y,w,z)
    

    I don't see other reasons, because matrix/vector operations don't work anyway on 4D arrays...