我怎样才能加快这个数组乘法?
How can I speed up this array multiplication?
for i = 1:N
for j = 1:M
for c = 1:3
A(:,:,c,i) = A(:,:,c,i).*B(:,:,j);
end
end
end
是否可以通过矢量化等方式消除最内层循环?
首先你可以通过预乘矩阵来消除j上的循环:
B2 = prod(B, 3); % Element-wise product along third dim
for i = 1:N
for c = 1:3
A(:,:,c,i) = A(:,:,c,i) .* B2;
end
end
然后你可以用repmat把Matrix B2平铺出来,消除另外两个循环。我很难理解 4D 矩阵,但它应该看起来像这样:
B2 = prod(B, 3); % Element-wise product along third dim
B3 = repmat(B2, [1 1 3 N]);
A = A .* B3;
或者(甚至更好)使用 bsxfun:
B2 = prod(B, 3); % Element-wise product along third dim
A = bsxfun(@times, A, B2);
bsxfun 将使用更少的内存,因为它 "virtually replicates" B2.
for i = 1:N
for j = 1:M
for c = 1:3
A(:,:,c,i) = A(:,:,c,i).*B(:,:,j);
end
end
end
是否可以通过矢量化等方式消除最内层循环?
首先你可以通过预乘矩阵来消除j上的循环:
B2 = prod(B, 3); % Element-wise product along third dim
for i = 1:N
for c = 1:3
A(:,:,c,i) = A(:,:,c,i) .* B2;
end
end
然后你可以用repmat把Matrix B2平铺出来,消除另外两个循环。我很难理解 4D 矩阵,但它应该看起来像这样:
B2 = prod(B, 3); % Element-wise product along third dim
B3 = repmat(B2, [1 1 3 N]);
A = A .* B3;
或者(甚至更好)使用 bsxfun:
B2 = prod(B, 3); % Element-wise product along third dim
A = bsxfun(@times, A, B2);
bsxfun 将使用更少的内存,因为它 "virtually replicates" B2.