@ Symbol in function handles as an input variable to another function
Show older comments
Hey guys i am currently trying to wrap my head around the concept of function-handles and there is one thing i am not understanding right now. I have the following function which i want to use as an input argument for another function
function[y]=fun2(x)
y = exp(-x.^2).*log(x).^2;
end
and then i have the other function
fun = @fun2
Q = integral(fun,0,inf)
Now the thing that i do not understand is; if i were to remove the @ sign it would tell me that i am missing input arguments and i am confused what does the @ sign change in terms of input arguments. Why do i need more input arguments when all that changed is that i didn't declare it as a function handle, but tried to open it directly? It is probably something elementary that i just didnt fully understand so advices would be highly appreciated.
Thank you in advance!
Accepted Answer
More Answers (2)
John D'Errico
on 24 Nov 2021
0 votes
Integral will only accept an input function as a function handle. The @ converts the m-file name into a function handle, that integral can accept. Some of the older tools would accept m-file names in quotes, at least in older releases. But I see that quadgk also requires a function handle input in my release.
I will add that infinite limits of integration will sometimes cause a strange to interpret failure, where you may be surprised at the result.
dpb
on 24 Nov 2021
The issue is given by the requirements of the function integral -- the help file for it reads in part--
>> help integral
integral Numerically evaluate integral.
Q = integral(FUN,A,B) approximates the integral of function FUN from A
to B using global adaptive quadrature and default error tolerances.
FUN must be a function handle. ...
...
The first argument to integral MUST be a function handle--in otherwords, a pointer to a function that integral can evaluate internally whatever it is that the user has declared to be the integrand. That's how the flexibility to integrate any function is achieved.
When you break that contract and pass a function name instead, the internals of integral try to evaluate the function as written, but the function needs an argument which isn't there.
It's just operator error in not living up to the requirements of integral
Categories
Find more on Loops and Conditional Statements 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!