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에서 Numerical 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