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]).

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Function Creation 的更多信息

产品


版本

R2017a

Community Treasure Hunt

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

Start Hunting!

Translated by