我可以在Matlab中通过舍弃for循环来优化下面的代码吗?
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
最佳答案
是的,你可以,使用第三维度来存储中间结果并将其转换回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 )