0
votes

The standard Matlab ode45 call is:

[T,Y] = solver(odefun,tspan,y0,options);

But I also want the value of odefunat each state vector Y. It seems like there should be an option to return something like

[T,Y, DYDT] = solver(odefun,tspan,y0,options);

as this would be the most efficient way, since the routine already evaluates the derivative at each point internally. The obvious work around is to do

DYDT = odefun(T,Y);

however then I would need to write a modified version of odefun since the one you pass to the solver should be a column vector denoting a single state. Here obviously I am wanting to calculate DYDT at all states Y returned by the solver. Any suggestions?

2

2 Answers

1
votes

I don't believe there is away to get the derivative directly.

May be you could try something like:

tspan = 0:0.001:5; % choose a time-interval
x0 = 5 % and an initial condition

run you ode45 code

[~,xt_solution]=ode45('odefun',tspan,x0);

and then diffenrentiate your solution:

tdiff=diff(tspan);
xdiff=diff(xt_solution);
dxdt=xdiff1./tdiff1;

And there you go. You will have the values of the derivative together with its corresponding tspan value! Just remember that your ´dxdt´ array will have one element less than xt_solution. This is because of the way we are differentiating xt_solution

If you must have both arrays of the same dim you can go:

if size(xt_solution,1) > size(dxdt,1)
    xt_solution = xt_solution(1:size(dxdt,1),:);
end

So the trick is to predefine your tspan from before and then use it to find the derivative!

0
votes

I think if you write your odefun to cope both with scalars and vectors (for example using .*), you should be able to do what you suggest (dydt = odefun(t,y);). Other than that, you can use a for loop to go through the time vector returned by the ode solver (maybe not very efficient, but pretty robust).

I don't think there is a way to have the ode solver return the derivative along with the solution.