使用 bsxfun 批处理外部产品

Batching outer products with bsxfun

假设我有 2 个向量,我想做一个外积。我可以使用:

A=x*y';

或者我可以这样使用 bsxfun

bsxfun(@times,x,y')

但是我想批量处理外部产品。我有 2 个矩阵,每个都有 p 个向量:

n=1000;  p=6;
A=rand(n,p);
D=rand(n,p);

我想计算所有的外积并对结果求和:

AA=zeros(n,n);

for j=1:p
    AA = AA + A(:,j) * D(:,j).';
end

我想更有效地执行此操作,但我不知道该怎么做。

只需将两个矩阵相乘即可​​:

n=1000;  p=6;
A=rand(n,p);
D=rand(n,p);

way1=zeros(n,n);

for j=1:p
    way1 = way1 + A(:,j) * D(:,j).';
end

way2 = A * D.';

any(way1(:) ~= way2(:))

毕竟可以使用bsxfun:

C = bsxfun(@times,A,permute(D,[3 2 1]));
result = sum(C,2);

第一行计算 AD 之间的所有外积,第二行根据要求将结果相加。

测试如下:

kk = 1e3;
times1 = zeros(kk,1);
n=1000;  p=6;
A=rand(n,p);
D=rand(n,p);
for ii = 1:kk
    tic
    C = bsxfun(@times,A,permute(D.',[3 1 2]));
    result = sum(C,2);
    times1(ii) = toc;
end
mean(times1)

bsxfun 需要 0.0456 秒,直接乘法需要 0.0075 秒,但我怀疑我的解决方案实际上做了 6 次,因为置换不在直接乘法中。所以每个外积bsxfun需要0.0076s,几乎相等。