ベクトルの各要素を関​数に渡して結果をベク​トルで取得したい

16 views (last 30 days)
Katsuto Tsujimoto
Katsuto Tsujimoto on 27 Mar 2020
Commented: Katsuto Tsujimoto on 27 Mar 2020
a, b, c3つの引数を持つ関数myfuncがあったとして、一つの引数だけを変化させたときのmyfuncの挙動を調べたいです。
このとき、すでにあるベクトルの各要素を関数に渡し、ベクトルの形で結果を取得するようにしたいのですが、そのような関数はMatlabにあるでしょうか。
forループを使って書けば次のようになります。
res = null(10);
for i = 1:10
tmp = myfunc(i,2,3);
res(i) = tmp;
end
disp(res)
function G = myfunc(a, b, c)
G = a*b+c;
end
あるいはMATLABではこういう場合forループを使うのが一般的なのでしょうか。
助言いただければ幸いです。

Accepted Answer

michio
michio on 27 Mar 2020
arrayfun を使って
res = arrayfun(@(x) myfunc(x,2,3), 1:10)
でもいいですし、そのままベクトルを入力してもOKな形に関数を実装していれば、
res = myfunc(1:10,2,3)
でも同じ結果になります。R2020a で試しましたが、古いバージョンだと2つ目の方法は怒られるかもしれません。
  1 Comment
Katsuto Tsujimoto
Katsuto Tsujimoto on 27 Mar 2020
michioさま
@で無名関数を作ればよかったのですね。初歩的な質問をしてしまい恐縮ですが、
たいへん助かりました。ありがとうございます。

Sign in to comment.

More Answers (0)

Categories

Find more on 構造体 in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!