什么是在matlab中减去两个单元格数组的最快方法

时间:2021-04-02 15:56:57

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.

假设我有两个单元阵列A和B,这些单元格中的每个元素都是N * M矩阵,例如:A = {[2 3; 4 5] [1 5; 7 8]}和B = {[1 2; 4 5] [7 9; 10 1]}两者都是细胞,每个元素是2 * 2矩阵。

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]}.

这将导致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 个解决方案

#1


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

如前所述,很大程度上取决于数据,但在您的示例中,最快的方法可能是嵌套for循环:

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

#2


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

您可以转换为3D数组,子关系,并转换回:

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.

当然,如果你可以避免转换,那就更快,也就是直接使用3D数组。

#1


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

如前所述,很大程度上取决于数据,但在您的示例中,最快的方法可能是嵌套for循环:

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

#2


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

您可以转换为3D数组,子关系,并转换回:

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.

当然,如果你可以避免转换,那就更快,也就是直接使用3D数组。