ODE45 change the value of a parameter at each time step
11 views (last 30 days)
Show older comments
Hello everyone,
I am trying to solve a differential equation of the form:
Assuming:
tspan =0:0.1:1;
beta =0.1;
x_0 = 0;
x_0_prime = 0;
x0 = [x_0 x_0_prime ]; %initial conditions
what I have written as VALUES is:
values=[0.6 0.8 0.9 1.4 2.5 0.6 0.7 0.8 0.9 1 2.3];
and it changes for each time step, meaning that tspan= 0 => values=0.6, at tspan 0.1 => values=0.8... and so on.
I was trying to find x using ode45, but I am having problems with chaning the VALUES for each time step.
I tried the following:
for i=1:numel(tspan)
[tspan,x]=ode45(@(tspan,x)rhs_x(tspan,x,values(i)),tspan,x0);
end
figure
plot(tspan,x(:,1))
function xdot=rhs_x(tspan,x,values)
beta=0.1;
xdot=[x(2);-2*beta*x(2)-x(1)-values];
end
This does not give correct results becasue it is just solving for x using, lets say the first value of VALUES=0.6, for all time steps, then finds x, and repeats again for the next value (but not changing VALUES for each time step as I want).
Thank you very much for your help!!
0 Comments
Answers (1)
Star Strider
on 7 Feb 2022
Try something like this —
tspan = 0:0.1:1;
values = [0.6 0.8 0.9 1.4 2.5 0.6 0.7 0.8 0.9 1 2.3];
beta = 0.1;
x_0 = 0;
x_0_prime = 0;
x0 = [x_0 x_0_prime]; %initial conditions
[tvc,xc]=ode45(@(t,x)rhs_x_c(t,x,values,tspan),tspan,x0);
figure
subplot(2,1,1)
plot3(tvc, values, xc(:,1))
grid
xlabel('t')
ylabel('values')
zlabel('x_1')
subplot(2,1,2)
plot3(tvc, values, xc(:,2))
grid
xlabel('t')
ylabel('values')
zlabel('x_2')
sgtitle('Linear')
figure
plot3(tvc, values, xc)
grid
xlabel('t')
ylabel('values')
zlabel('x')
title('Linear')
legend('x_1','x_2', 'Location','eastoutside')
[tvd,xd]=ode45(@(t,x)rhs_x_d(t,x,values,tspan),tspan,x0);
figure
subplot(2,1,1)
plot3(tvd, values, xd(:,1))
grid
xlabel('t')
ylabel('values')
zlabel('x_1')
subplot(2,1,2)
plot3(tvd, values, xd(:,2))
grid
xlabel('t')
ylabel('values')
zlabel('x_2')
sgtitle('Stepwise')
figure
plot3(tvd, values, xd)
grid
xlabel('t')
ylabel('values')
zlabel('x')
legend('x_1','x_2', 'Location','eastoutside')
title('Stepwise')
function xdot=rhs_x_c(t,x,values,tspan)
value = interp1(tspan,values,t);
beta=0.1;
xdot=[x(2);-2*beta*x(2)-x(1)-value];
end
function xdot=rhs_x_d(t,x,values,tspan)
value = interp1(tspan,values,t, 'next');
beta=0.1;
xdot=[x(2);-2*beta*x(2)-x(1)-value];
end
The first is the ‘classic’ way to solve such problems, because ‘t’ is essentially continuous, not discrete, so interpolation is appropriate.
Other methods of interpolation (rather than the default 'linear') are possible. Using 'next' produces the second result.
Choose the interpolation method that produces the desired result.
.
0 Comments
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!