MATLAB: How to use function handle for “defavl” function when it is used with “fzero” function

function handleMATLABOptimization Toolbox

I am trying to use function handle with "deval" function. I checked the "Optimize an ODE in Parallel " example it has what I want but there is something that I don't get it in the code,here is a part of the code :
function f = cannonobjective(x)
x0 = [x(1);0;300*cos(x(2));300*sin(x(2))];
sol = ode45(@cannonfodder,[0,15],x0);
% Find the time t when y_2(t) = 0
zerofnd = fzero(@(r)deval(sol,r,2),[sol.x(2),sol.x(end)]);
How 'r' is passed to the deval function, Although it is not defined earlier? According to the documentation, 'r' is a vector of some points used to evaluate the solution( sol structure) of the ode45 solver.

Best Answer

In the example you gave, the first argument to fzero must be a function which takes a scalar and returns a scalar. In your example, that function is
@(r)deval(sol,r,2)
which is an anonymous function. It takes a scalar, r, and returns the result of deval(sol,r,2), also a scalar. fzero passes different values of r into your anonymous function, looking for the value where your anonymous function would return 0, or rather where deval(sol,r,2) would return 0.
Related Question