フィルターのクリア

Calling different anonymous functions from a for loop

7 ビュー (過去 30 日間)
Braden Kerr
Braden Kerr 2020 年 11 月 25 日
コメント済み: Braden Kerr 2020 年 11 月 25 日
Hello,
I have four functions that I need to call various values for and I was wondering if I can make this process faster by creating a four loop to iterate through the various functions. For example, I have four functions q(nu) listed below
q_1 = 1; % Lax-Friedrichs
q_2 = @(x) abs(x); % FIrst-order Upwind
q_3 = @(x) x^2; % Lax-Wendroff
q_4 = @(x) (1/3)+(2/3)*x^2; % Minimun Dispersion
And I have four values of nu,
nu = [1.0; 0.75; 0.50; .25];
is it possible to take these equations and put them in an array to call each function when I need it?
For example, I know this isnt how the code would be written, but I am just trying to show what I mean most clearly.
q_array = [q_1; q_2; q_3; q_4];
for i = 1:4
for j = 1:4
q_array(i(j));
end
end
In this, the idea would be to call each nu value for the first q, then call each nu value for the second q and so on.
I just dont know if Matlab syntax supports this since it q_array would turn each anonymous function into an argument and no longer a function, and I know having each array element of q_array as an anonymous function deosnt work because I tried this and it doesnt work.
q_array = [1; @(x) abs(x); @(x) x^2; @(x) (1/3)+(2/3)*x^2];

採用された回答

Walter Roberson
Walter Roberson 2020 年 11 月 25 日
q_array = {@(x)ones(size(x)); @(x) abs(x); @(x) x.^2; @(x) (1/3)+(2/3)*x.^2} ;
Now you can
q_array{i}(nu(j))
However I also vectorized the functions so instead of an inner loop,
q_array{i}(nu)
  3 件のコメント
Walter Roberson
Walter Roberson 2020 年 11 月 25 日
That what vectorizing is for, to apply the same calculation to each element individually but in an efficient way
Braden Kerr
Braden Kerr 2020 年 11 月 25 日
Got it, thanks

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

その他の回答 (0 件)

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by