Vectorizing Loops over Matrix Elements

I was wondering if there is a general method for vectorizing code of the form:
A = zeros(n,m);
for i = 1:n
for j = 1:m
A(i,j) = f[i, j]
end
end
where f[i,j] is some function of i and j.

 採用された回答

Torsten
Torsten 2023 年 5 月 23 日
移動済み: Torsten 2023 年 5 月 23 日

0 投票

If the function f "knows" how to cope with two vectors as inputs that don't have the same size: Yes.
E.g.
n = 3;
m = 5;
f = @(i,j) i.'*j;
A = f(1:n,1:m)
A = 3×5
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15

3 件のコメント

Tate Tower
Tate Tower 2023 年 6 月 5 日
Thanks for your help! Can you explain what line 3 is doing? I'm not sure what the @(i,j) part of the code does. Is this where I insert my function?
Thanks
Torsten
Torsten 2023 年 6 月 5 日
編集済み: Torsten 2023 年 6 月 5 日
f is a function handle that depends on the formal inputs i and j:
Tate Tower
Tate Tower 2023 年 6 月 5 日
Got it. Thanks for your help!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

製品

リリース

R2022b

質問済み:

2023 年 5 月 23 日

コメント済み:

2023 年 6 月 5 日

Community Treasure Hunt

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

Start Hunting!

Translated by