Search code examples
matlabsimulationodedifferential-equations

How to save an output variable using ode45 [MATLAB]?


I have a second order differential equation

function Xdot =second_order(t,X)
y=X(1);
y_d=X(2);

Xdot=zeros(2,1);
Xdot(1)=y_d;
Xdot(2)= -5*y_d-7;   
y_dd=Xdot(2);
end

Using MATLAB ode45 command, I am able to simulate it [t,X]=ode45(@(t,X)second_order(t,X),tspan,X0); I am able to capture the two state variables y and y_d in vectors as a function of time in this manner.

I want to capture y_dd in vector as a function of time but I am unable to save it. How can I treat it as an output variable? I have tried the following change to my function file function [Xdot,y_dd] =second_order(t,X) but i don't understand how to use the ode45 command so I can save y_dd as well during its execution.


Solution

  • Just evaluate the second_order function on the trajectory points. The second component of the result is the desired derivative.

    You also have evaluation function deval that can access the "dense output" interpolation of the solution and the slopes at those points, see https://de.mathworks.com/help/matlab/ref/deval.html#bu7i1mf

    sol=ode45(@second_order,[tspan(1) tspan(end)] ,X0); 
    [X,Xp] = deval(sol,tspan)
    

    You should find that the first derivatives in X(:,2) and Xp(:,1) are (almost) identical, the second derivative is then in Xp(:,2).