Search code examples
matlabcell-array

what's the fastest way to subtract two cell arrays in matlab


Pretend I have two cell arrays A and B, each element in those cells is N*M matrix, example :
A={ [2 3;4 5] [1 5;7 8]} and B={ [1 2;4 5] [7 9;10 1]} both are cells each element is 2*2 matrix.

Now I can subtract those cell arrays element-wise like this:

C=cellfun(@minus,A,B,'UniformOutput',false);

this will result in C={[1 1;0 0] [-6 -4;-3 7]}.

Now is that the fastest way ? or is there a faster approach ?

Consider cells with large number of matrices each matrix is small.


Solution

  • As already mentioned a lot depends on the data, but in your example the fastest way is probably a nested for loop:

    A={ [2 3;4 5] [1 5;7 8]};
    B={ [1 2;4 5] [7 9;10 1]};
    tic
    C=cellfun(@minus,A,B,'UniformOutput',false);
    toc
    tic
    s = size(A);
    for ii=1:s(1)
      for jj=1:s(2)
        D{ii,jj} = A{ii,jj}-B{ii,jj};
      end
    end
    toc
    isequal ( C, D )
    

    output:

    Elapsed time is 0.001420 seconds.
    Elapsed time is 0.000017 seconds.
    
    ans =
    
         1