MATLAB: How to extract value at a given time in ode 45

MATLABode45plot

I have solved an ode numerically for tspan [0 5] so an array is created for values of x at different t. The question is hoe can I extract value of x near say 2 and print it. I am asking this because I need to plot x(2.3) against a parameter.

Best Answer

Hi Shubham, use an events functions, see the example below. With events functions you can identify zero crossings; in your case (when t = 2.3) the zero crossing you would want to detect is for the expression: t - 2.3. In the command where ode45 is called below MATLAB returns te and ye the time of the event and the value of the function at this time.
%user parameters
N = 45742000; %total population

I0 = 1; %initial infected population
r0 = 12.9; %reproductive value
R0 = 0;%initial recovered population
i_period = 9; %duration of infectious period
tspan = [1, 50]; %length of time to run simulation over
%rate constant calculations
mu = 1 / i_period; %recovery rate
beta = r0 * mu / N; %infection rate
S0 = N - I0 - R0; %initial susceptible population
N0 = I0 + R0 + S0; %total population
%---------------------------------------------------
%feeding parameters into function
pars = [beta, mu, N, r0];
y0 = [45742000 1 0 0];
%using the ode45 function to perform intergration
options = odeset('Events',@events);
[t,y,te,ye,ie] = ode45(@sir_rhs, tspan, y0, options, pars);
figure(1)
plot(t,y(:,2),t,y(:,4));
xlim(tspan);
ylabel('Population (n)');
xlabel('Time (days)');
legend('Infected','Location','SouthEast');
function f = sir_rhs(~,y,pars)
f = zeros(4,1);
f(1) = -pars(1)*y(1)*y(2);
f(2) = pars(1)*y(1)*y(2) - pars(2)*y(2);
f(3) = pars(2) * y(2);
f(4) = y(2);
end
function [value,isterminal,direction] = events(t,~,~)
value = t - 20; % This would be your 2.3 (t - 2.3)
isterminal = 0; % Do not stop the integration when zero is detected
direction = 0; % Detect all zeros
end