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 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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,
0 commentaires
Réponse acceptée
Ameer Hamza
le 22 Sep 2020
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 commentaires
Steven Lord
le 22 Sep 2020
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]).
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Function Creation dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!