# Approximating derivative of numerical solution within event function

9 views (last 30 days)
Shant Danielian on 10 Jul 2017
Commented: Shant Danielian on 24 Jul 2017
The issue I have is having to compute the derivative (in real time) of the solution produced by ode45 within the events function.
Some pseudo-code to explain what I'm mean is,
function dx = myfunc(t,x,xevent)
persistent xevent
% xevent is the solution at the event
dx(1) = x(2);
dx(2) = complicated function of x(1),x(2), and xevent;
end
function [value,isterminal,direction] = myeventfcn(t,x)
position = function of x(1), x(2), and dx(2);
isterminal = 1;
direction = 0;
end
I know that if I didn't need to use the solution at the event within `myfunc` I could just compute dx=myfunc(t,x) within my event function and use `dx(2)`, yet since `xevent` is used within `myfunc` I can't input `xevent`.
I know there is a way of inputting constant parameters within the event function, but since it's the solution at the event location, which also changes, I'm not sure how to go about doing that.
My work around to this is to approximate `dx(2)` using the solution `x`. What I wanted to know is if it will be satisfactory to just use a finite difference approximation here, using a small fixed step size relative to the step size od45 takes, which is a variable step size.
Thanks for any help!
Shant Danielian on 24 Jul 2017
Thank you Walter, that fixed the issue and the code runs.

Walter Roberson on 10 Jul 2017
parameterize both the ode function and the event function to pass in xevent
Do not make xevent persistent within the ode function: when you do that, the variable's identity as persistent overrides the value passed in as a parameter.
If xevent is something being calculated inside the ode function rather than something being passed in, then do not try to remember it for later use in the event function by using persistent or global or a shared variable: There are circumstances under which ode45 might not call the event function for a while, and there are circumstances under which ode45 might call the event function several times in a row with different parameters without calling the ode function between. Therefore any value that you calculate in the ode function that you would like to also use in the event function needs to be recalculated in the event function.
Shant Danielian on 11 Jul 2017
That's exactly what I did. I stopped the solver when the discontinuity occurs, inputted a new xevent and restarted the solver at the updated initial conditions. I'm just a little confused on how to use the parameterization to input the xevent and the rest of the parameters that calculate dx(2) into the event function. The event I'm looking for is a function of dx(2) as well.