Do vector fields mapping R^2 to R^2 have to be coded in separate function files, or can I define anonymous functions for them directly in the script file?

1 回表示 (過去 30 日間)
Hi,
I've been writing functions from R^2 to R^2, i.e. F( f_1(x,y), f_2(x,y) )= (z_1, z_2), in separate function files, and then calling F in a script file. Could I instead write the two component functions f_1 and f_2 as anonymous functions directly in the script file? I read something on the Mathworks documentation that an anonymous function can only have one "executable" statement, but I'm not sure what that means.
Thanks,

採用された回答

Ameer Hamza
Ameer Hamza 2020 年 9 月 22 日
Can MATLAB anonymous function return two outputs?
Yes, for example
>> f = @(x) deal(x, x^2);
>> [a, b] = f(2)
a =
2
b =
4
But then you will always need to call it with two output arguments. The following will not work
>> a = f(3)
Error using deal (line 37)
The number of outputs should match the number of inputs.
So it is better to write a function in seperate file to handle such cases.
"anonymous function can only have one "executable" statement"
It means that you cannot do something like the following in an anonymous function
f = @(x) y=1, x+y; % not allowed
f = @(x) if x=1, y=2, end; % not allowed
"if the function file name is "nonlinear_equations", then in the script file, I store a variable f = @nonlinear_equations, and then use f instead."
Yes, you can directly use nonlinear_equations instead of f; there will be no difference. However, it is not entirely useless. For example, instead of nonlinear_equations, you need to use some other function. In the current code, you will only need to change the line: f = @new_function; however, in the other case, you will need to change it everywhere.
  9 件のコメント
Steven Lord
Steven Lord 2020 年 9 月 22 日
That's an example demonstrating that what I wrote works. F([1, 2]) should return a two element vector, the first element of which is f_1([1, 2]) and the second is f_2([1, 2]).
Noob
Noob 2020 年 9 月 22 日
Hi Steve,
Ok, got it -- thanks!

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumerical Integration and Differentiation についてさらに検索

製品


リリース

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by