我可以通过抛弃for循环来优化Matlab中的以下代码吗?
A = [];
B = randn(4,8);
C = randn(8,4);
I = randperm(8,3);
J = randperm(8,3);
for i = 1:3
A = [A kron(C(J(i),:)',B(:,I(i)))];
end
答案 0 :(得分:4)
是的,您可以使用第三维存储中间结果并将其转换回2D。这样你也可以避免kron
本身,这本身并不是最快的。
Matlab R2016a或更高版本:
a = C(J,:).' .* permute(B(:,I),[3 2 1]); %// calculation of the product to 3rd dimension
%// by implicit expansion
b = permute( a, [3 1 2] ); %// permuting
out = reshape( b, [], 3 ) %// reshape to desired form
短:
out = reshape( permute( C(J,:).' .* permute(B(:,I),[3 2 1]), [3 1 2] ), [], 3 )
在Matlab R2016a之前:
a = bsxfun(@times , C(J,:).', permute(B(:,I),[3 2 1])); %// calculation of
%// the product to 3rd dimension(explicit)
b = permute( a, [3 1 2] ); %// permuting
out = reshape( b, [], 3 ) %// reshape to desired form
简短:
out = reshape(permute(bsxfun(@times , C(J,:).', permute(B(:,I),[3 2 1])), [3 1 2] ), [], 3 )
答案 1 :(得分:1)
以下是使用kron
的矢量化版本(不像thewaywewalk的答案那么快):
kron(C(J,:).', ones(size(B,1),1)) .* kron(ones(size(B,1),1), B(:,I))