假设我有两个矩阵A和B,其中: A是100x2 B是5×2
我想通过B中的每个元素减去A的每个元素。我可以运行以下内容来实现我想要的:
for j = 1:5
D = A - B(j, :);
C = [C(:,:); D(:,:)];
end;
for j = 1:5
D = A - B(j, :);
C = [C(:,:); D(:,:)];
end;
然而,对于巨大的矩阵来说这很慢。我所有尝试对此进行矢量化都会遇到“不一致的参数”的错误
如何压缩上面的for循环来使用矢量化?j = 1:5;
C = A - B(j, :);
答案 0 :(得分:2)
Permute axes,使用bsxfun
进行广播减法,reshape
至2D
-
reshape(bsxfun(@minus, permute(A,[1,3,2]), permute(B,[3,1,2])),[],2)
使用implicit-broadcasting/implicit-expansion
-
reshape(permute(A,[1,3,2]) - permute(B,[3,1,2]),[],2)
示例运行 -
>> A
A =
1 2
4 8
>> B
B =
3 2
5 6
% Original loopy code
>> C = [];
for j = 1:size(B,1)
D = bsxfun(@minus, A, B(j, :));
C = [C(:,:); D(:,:)];
end;
>> C
C =
-2 0
1 6
-4 -4
-1 2
% Proposed code
>> reshape(bsxfun(@minus, permute(A,[1,3,2]), permute(B,[3,1,2])),[],2)
ans =
-2 0
1 6
-4 -4
-1 2
答案 1 :(得分:1)
这样的事可能会对你有所帮助:
arrayfun(@(x) x*B, A, 'Uni', 0)