Arrays 使用索引kronecker乘积生成的向量构建矩阵,而不使用for循环
我可以通过舍弃for循环在Matlab中优化以下代码吗Arrays 使用索引kronecker乘积生成的向量构建矩阵,而不使用for循环,arrays,matlab,vectorization,Arrays,Matlab,Vectorization,我可以通过舍弃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 是的,您可以,使用三维存储中间结果并将其转换回二维。这样你也可以避免kron本身不是最快的 Matlab R2016a或更高版本: a = C(J,:).' .* permu
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
是的,您可以,使用三维存储中间结果并将其转换回二维。这样你也可以避免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
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( C(J,:).' .* permute(B(:,I),[3 2 1]), [3 1 2] ), [], 3 )
在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
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 )
下面是一个使用
kron
的矢量化版本(速度不如的答案):