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来平铺矩阵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将使用更少的内存,因为它"实际上复制"了B2。