我需要取一个矩阵的每个列向量与另一个矩阵的每个列向量的外积
Example:
A=[1,2,3; 3,1,4; 4,1,3]
B=[2,1,3; 4,1,2; 3,2,1]
for each column of "A", I want to take it's outer product with each column of "B" and sum them all. I can do it in a loop but it is slow. Is there any other way of doing it fast?.
for example:
U=zeros(3,3)
for n=1:size(A,1)
for m=1:size(B,1)
U=U+A[:,n]'*B[:,m]
end
end
我想这就是问题想要的:
function outsum1(A,B)
U = zeros(size(A,1), size(B,1))
for n=1:size(A,1) # independent loops n and m
for m=1:size(B,1)
U = U + A[:,n]*B[:,m]' # transpose the second for outer product?
end
end
U
end
A = [1 2 3; 3 1 4; 4 1 3]; # can't mix , (vectors) and ; / space (concatenation)
B = [2 1 3; 4 1 2; 3 2 1]
outsum1(A,B) == [36 42 36; 48 56 48; 48 56 48]
如果是这样,有一些方法可以使这个函数更有效(例如@views U .= U .+ A[:,n] .* B[:,m]'
)。但最重要的一点可能是要注意这些循环不一定是嵌套的。在索引符号中:
U[i,j] = sum_m,n A[i,n] * B[j,m]
= (sum_n A[i,n]) * (sum_m B[j,m])
第一种形式有4个嵌套循环,第二种形式只有2个。所以对于大A
,这个函数会快得多,大约是length(A)
的一个因子:
outsum2(A,B) = sum(A, dims=2) .* sum(B, dims=2)'
outsum2(A,B) == [36 42 36; 48 56 48; 48 56 48] # same answer
另一个答案解释了"一个矩阵的每个列向量与另一个矩阵的每个列向量的外积";表示对列求和,而不是两列。这是非常不同的,在索引符号中它是:
U[i,j] = sum_n A[i,n] * B[j,n]
这是矩阵乘法,U = A * B'
。