gpt4 book ai didi

arrays - 使用由索引的 kronecker 产品产生的向量构建矩阵,无需 for 循环

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:11 24 4
gpt4 key购买 nike

我可以通过放弃 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

短:

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 )

关于arrays - 使用由索引的 kronecker 产品产生的向量构建矩阵,无需 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41871381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com