evaluation of anonymous function
Show older comments
r=1e-2;
V0=1e-6;
m=1;
if(m<4)
V=@(x) (0.5+0.5.*sign(r.^2-x.^2))*V0;
else
abort
end
In this piece of code, how are the values assigned to V?
The fuction V is not used in any other block of code. What are the values of x? How is V evaluated?
Please clarify this?
Accepted Answer
More Answers (1)
Jorg Woehl
on 5 Mar 2021
I am not quite sure if this is what you are asking, but I'll give it a shot:
The piece of code important to your question is
r=1e-2;
V0=1e-6;
V=@(x) (0.5+0.5.*sign(r.^2-x.^2))*V0;
The sign function inside the anonymous function returns three possible values for real numbers: -1 for negative arguments, 0 if the argument is zero, and 1 for positive arguments.
Therefore, the result of the operation 0.5+0.5*sign(arg) is limited to 0 for negative arguments, 0.5 if arg is zero, and 1 for positive arguments. This is then multiplied by V0 and returned when you call the anonymous function with some argument x.
As a result, when calling V(x) the output can be one of the following:
- 0 if
, i.e.
or 
for 
anywhere else, i.e. 
For complex numbers, the sign function returns complex numbers with real and imaginary parts varying freely between -1 and 1, so the story is more interesting there.
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!