Reputation: 2673
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.
Upvotes: 2
Views: 1640
Reputation: 5672
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
Upvotes: 1
Reputation: 112679
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.
Upvotes: 3