问题描述
我试图向量化某个加权总和,但不知道该怎么做.我在下面创建了一个简单的最小工作示例.我猜该解决方案涉及bsxfun或reshape和kronecker产品,但我仍然没有设法使其正常工作.
I was trying to vectorize a certain weighted sum but couldn't figure out how to do it. I have created a simple minimal working example below. I guess the solution involves either bsxfun or reshape and kronecker products but I still have not managed to get it working.
rng(1);
N = 200;
T1 = 5;
T2 = 7;
A = rand(N,T1,T2);
w1 = rand(T1,1);
w2 = rand(T2,1);
B = zeros(N,1);
for i = 1:N
for j1=1:T1
for j2=1:T2
B(i) = B(i) + w1(j1) * w2(j2) * A(i,j1,j2);
end
end
end
A = B;
推荐答案
您可以使用bsxfun
,reshape
和permute
的组合来完成此操作.
You could use a combination of bsxfun
, reshape
and permute
to accomplish this.
我们首先使用permute
将N
尺寸移动到A
的第3尺寸.然后,我们将w1
和w2
的转置相乘以创建权重网格.然后,我们可以使用bsxfun
在此网格与A
的每个切片"之间执行逐元素乘法(@times
).然后,我们可以将3D结果整形为M x N,并在第一个维度上求和.
We first use permute
to move the N
dimension to the 3rd dimension of A
. We then multiply w1
and the transpose of w2
to create a grid of weights. We can then use bsxfun
to perform element-wise multiplication (@times
) between this grid and each "slice" of A
. We can then reshape the 3D result into M x N and sum across the first dimension.
B = sum(reshape(bsxfun(@times, w1 * w2.', permute(A, [2 3 1])), [], N)).';
更新
实际上有一种更简单的方法,该方法将使用矩阵乘法为您执行求和.不幸的是,它必须分为
There's actually a simpler approach which would use matrix multiplication to perform the summation for you. It unfortunately has to be broken into
% Create the grid of weights
W = w1 * w2.';
% Perform matrix multiplication between a 2D version of A and the weights
B = reshape(A, N, []) * W(:);
或者您可以使用kron
创建扁平化的权重网格:
Or you could use kron
to create the flattened grid of weights:
B = reshape(A, N, []) * kron(w2, w1);
这篇关于向量化加权和Matlab的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!