Matrix-vector operations without loops

5 ビュー (過去 30 日間)
Valeri Aronov
Valeri Aronov 2021 年 10 月 14 日
編集済み: Valeri Aronov 2021 年 10 月 14 日
How do I do this without loops:
HessW = rand(length(x), length(x), length(f));
GradW = rand(length(x), length(f));
A = zeros(length(x));
for i=1:length(f)
for j=1:length(x)
for k=1:length(x)
A(j) = A(j) + 2*HessW(j,k,i)*GradW(k,i);
end
end
end
Thanks

採用された回答

Matt J
Matt J 2021 年 10 月 14 日
編集済み: Matt J 2021 年 10 月 14 日
A=2*(HessW(:,:)*GradW(:));
  1 件のコメント
Valeri Aronov
Valeri Aronov 2021 年 10 月 14 日
編集済み: Valeri Aronov 2021 年 10 月 14 日
!!! Hats off.
Further 'improvement' ;-)
A=2*HessW(:,:)*GradW(:);

サインインしてコメントする。

その他の回答 (1 件)

Rik
Rik 2021 年 10 月 14 日
You can use permute to reshape the second array and use the implicit expansion to do the multiplication in one go. Then sum over two dimensions to get your vector.
Note that you shouldn't use length. Use numel or size instead.
x=rand(5,1);f=rand(3,1);
HessW = rand(numel(x), numel(x), numel(f));
GradW = rand(numel(x), numel(f));
A=2*HessW.*permute(GradW,[3 1 2]);
sum(A,[2 3])
ans = 5×1
9.8738 8.3109 7.6960 9.2496 9.0811
A = zeros(length(x));
for i=1:length(f)
for j=1:length(x)
for k=1:length(x)
A(j) = A(j) + 2*HessW(j,k,i)*GradW(k,i);
end
end
end
A
A = 5×5
9.8738 0 0 0 0 8.3109 0 0 0 0 7.6960 0 0 0 0 9.2496 0 0 0 0 9.0811 0 0 0 0
  2 件のコメント
Rik
Rik 2021 年 10 月 14 日
Comment posted by @Valeri Aronov as an answer:
Gosh! I am thinking of keeping the loops for readability. Is that because I am such an inept reader of MATLAB code? ;-)
Rik
Rik 2021 年 10 月 14 日
You can split it up in steps. You should also include comments that explain why you are doing what you're doing.
%change the order of dimensions so this is a 1xNxN array
GradW_permuted=permute(GradW,[3 1 2]);
%do element-wise multiplication
A=2*HessW.*GradW_permuted;
%sum over the second and third dimension to get the vector
A=sum(A,[2 3])
These comments don't explain the purpose, because your question did not do so.
I would not suggest leaving in the loops, as they harm the performance of the code.
If you worry about readability of you code, make sure to write comments. Explain what you're doing. I often say half you text should be green. That is overdoing it, but your functions should have documentation and you code should have comments.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

製品


リリース

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by