How can I plot the derivatives of the components of the solution to a system of ODEs?

2 vues (au cours des 30 derniers jours)
I have the following code for the function solving a system of ODEs:
function dwdt=coupled(t,w)
beta=1+exp(-t);
delta=2+exp(-t);
gama=exp(-t);
f1=1/(t+1);
f2=1/(t+2);
r1=1/(t+2)^2;
r2=2/(t+1)^2;
dwdt=zeros(4,1);
dwdt(1)=w(2)-f1*w(1);
dwdt(2)=-beta*w(1)-f1*w(2)+gama*w(3)-r1*w(1)^2;
dwdt(3)=w(4)-f2*w(3);
dwdt(4)=gama*w(1)-delta*w(3)-f2*w(4)-r2*w(3)^2;
xdot=w(2)-f1.*w(1);
end
With the commands
>> tspan = [0 50];
z0=[0.01 0.01 0.01 0.01];
[t,z] = ode45(@(t,z) coupled(t,z), tspan, z0);
figure
plot(t,z(:,1),'r',t,z(:,3),'b');
legend('x(t)','y(t)');
I have plotted the first w(1) and the third w(3) components of the solution. But I want also to plot on the same interval, with the same initial data, the derivatives of w(1) and w(3), i.e.,
dwdt(1)=w(2)-f1*w(1)
and
dwdt(3)=w(4)-f2*w(3)
If I add the command line
plot(t,z(:,1),'r',t,z(:,2)-f1*z(:,1),'b');
I get the message
Unrecognized function or variable 'f1'.
How dwdt(1) and dwdt(3) can be plotted ?

Réponse acceptée

Star Strider
Star Strider le 20 Sep 2021
The only way is to use al loop —
tspan = [0 50];
z0=[0.01 0.01 0.01 0.01];
[t,z] = ode45(@(t,z) coupled(t,z), tspan, z0);
for k = 1:numel(t)
dwdt(:,k) = coupled(t(k),z(k,:));
end
figure
plot(t,z(:,1),'r',t,z(:,3),'b')
hold on
plot(t, dwdt(1,:), ':r')
plot(t, dwdt(3,:), ':b')
hold off
legend('$x(t)$','$y(t)$','$\frac{dx(t)}{dt}$','$\frac{dy(t)}{dt}$', 'Interpreter','latex', 'Location','best');
function dwdt=coupled(t,w)
beta=1+exp(-t);
delta=2+exp(-t);
gama=exp(-t);
f1=1/(t+1);
f2=1/(t+2);
r1=1/(t+2)^2;
r2=2/(t+1)^2;
dwdt=zeros(4,1);
dwdt(1)=w(2)-f1*w(1);
dwdt(2)=-beta*w(1)-f1*w(2)+gama*w(3)-r1*w(1)^2;
dwdt(3)=w(4)-f2*w(3);
dwdt(4)=gama*w(1)-delta*w(3)-f2*w(4)-r2*w(3)^2;
xdot=w(2)-f1.*w(1);
end
Experiment to get different results.
.
  20 commentaires
Cris19
Cris19 le 23 Sep 2021
I have defined the new functions f1, f2
if t >= 1
f1 = 1/t;
else
f1 = -2*t^2+3*t;
end;
if t >= 2
f2 = 1/(t-1);
else
f2 = -(3/4)*t^2+2*t;
end;
and h1, h2
if t>=1
h1 = -1/t^2;
else
h1=-4*t+3;
end;
if t>=2
h2 = -1/(t-1)^2;
else
h2 = -(3/2)*t+2;
end;
in the new example, given in today's question.
I get no errors and the compiler does not seem to need restarting.
Thank you so very much, I have learned many new and interesting things and I hope I did not bother you too much.
Star Strider
Star Strider le 23 Sep 2021
As always, my pleasure!
No worries, no bother!
.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by