Vectorizing loop containing multiplication of a scalar and a matrix

3 ビュー (過去 30 日間)
Masa
Masa 2022 年 2 月 4 日
コメント済み: Masa 2022 年 2 月 4 日
How to implement the following algorithm in a vectorized manner? (Preferably without using functions other than `mat`)
mat = @(i) [i-1, i, 0; i, i+1, 0; 0, 0, 1];
w = [0.2,0.5,1,0.5,0.2];
s = 0;
for j = 1:5
s = s + w(j)*mat(j);
end
the result is
s =
4.8 7.2 0.0
7.2 9.6 0.0
0.0 0.0 2.4

採用された回答

Bruno Luong
Bruno Luong 2022 年 2 月 4 日
編集済み: Bruno Luong 2022 年 2 月 4 日
w = [0.2,0.5,1,0.5,0.2];
i=reshape(1:length(w),1,1,[]);
z = zeros(size(i));
s=sum([i-1, i, 0+z; i, i+1, 0+z; 0+z, 0+z, 1+z].*reshape(w,size(i)),3)
s = 3×3
4.8000 7.2000 0 7.2000 9.6000 0 0 0 2.4000
  6 件のコメント
Bruno Luong
Bruno Luong 2022 年 2 月 4 日
編集済み: Bruno Luong 2022 年 2 月 4 日
"so in such situations using for loop is inevitable."
No you can use ARRAYFUN but that is no better (worse) than the for-loop
mat = @(i) [i-1, i, 0; i, i+1, 0; 0, 0, 1];
w = [0.2,0.5,1,0.5,0.2];
i = 1:5;
M=arrayfun(mat, i, 'unif', 0);
wdM = arrayfun(@(w,mc) w*mc{1}, w, M, 'unif', 0);
s=sum(cat(3,wdM{:}),3)
s = 3×3
4.8000 7.2000 0 7.2000 9.6000 0 0 0 2.4000
If you prefer such cryptic code instead of for-loop just go ahead.
Masa
Masa 2022 年 2 月 4 日
Thanks, of course I'd rather using loops. I thought there might be some workaround using built-in functions of MATLAB (except 'arrayfun') to do the summation mentioned in the code more efficiently.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by