Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 使用索引kronecker乘积生成的向量构建矩阵,而不使用for循环_Arrays_Matlab_Vectorization - Fatal编程技术网

Arrays 使用索引kronecker乘积生成的向量构建矩阵,而不使用for循环

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

我可以通过舍弃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,:).' .* 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
的矢量化版本(速度不如的答案):