Clear Filters
Clear Filters

How to use function handle for "defavl" function when it is used with "fzero" function?

1 view (last 30 days)
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.

Accepted Answer

Tommy
Tommy on 8 Apr 2020
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.
  1 Comment
Mohamed Abdullah
Mohamed Abdullah on 8 Apr 2020
Edited: Mohamed Abdullah on 8 Apr 2020
Thanks for answering my question. Now I understand the code . So the fzero function passes the values of 'r' from the range of its second argument ([sol.x(2),sol.x(end)])to deval function to evaluate the solution 'sol' at each value of 'r'.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!