1
votes

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.

2
It depends how many of those matrices you have in your cell array and how you want your output. Generally your approach is quite good, Using the relatively slow cell2mat you could create a 3D-matrix, Calculations then are faster, but as cell2mat and mat2cell are slow, it really depends on your data size.Robert Seifert
@thewaywewalk thanks, I edited my questionniceman
The fastest way to subtract two cell arrays, is not to work with cell arrays to begin with. If you can subtracts them, they must have the same dimensions, then dont work with cells, matrices will do.bla
@bla I have to seperate an array into submatrices, I used cell2mat and didn't find another solution, in other words I have to work with cell arraysniceman
you have nXm matrices of the same kind, not nXm and kxJ, you can arrange them in N dimensional arrays anyway you want. edit the question with a relevant example and you'll see how to do this.bla

2 Answers

1
votes

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
3
votes

You could convert to a 3D array, subtact, and convert back:

mat2cell(cat(3, A{:}) - cat(3, B{:}), size(A{1},1), size(A{1},2), [1 1]);

Of course it would be faster if you could avoid the conversions, that is, work with 3D arrays directly.