How can i vary the value of one parameter and plot them on same graph?

4 views (last 30 days)
Hi there!
function idtry
%
r = 1.3;
tspan = [0:20:40];
%
sol = dde23(@ddems,r,@ddemshist,tspan);
time = sol.x;
SD = sol.y(1,:);
ID = sol.y(2,:);
VD = sol.y(3,:);
hold on
plot(time,SD,'b','LineWidth',2)
plot(time,VD,'g','LineWidth',2)
hold off
plot(time,ID,'--r','LineWidth',2)
xlabel('Time(days)');
ylabel('Infected Dogs Population');
legend('I_d')
grid on
grid minor
function s = ddemshist(t)
% Constant history function for DDEX1.
s = [40 0 0]';
% --------------------------------------------------------------------------
function dydt = ddems(t,y,Z)
Ad = 15; mud = 0.2; k = 2.9; cd = 0.01;
Bd = 0.4; r = 0.2; md = 0.02;
% Differential equations function for DDEX1.
ylag1 = Z(:,1);
dydt = [ Ad-Bd*y(1)*ylag1(1)*exp(-mud*r)-(mud+k)*y(1)+cd*y(3)
Bd*y(1)*ylag1(1)*exp(-mud*r)-(mud+md)*y(2)
k*y(1)-(cd+mud)*y(3)
];
I want to vary the value of k to be [0.8, 1.6, 2.4, 2.9] and plot on the same graph.. how can i do that please?

Accepted Answer

Voss
Voss on 17 Feb 2023
Edited: Voss on 18 Feb 2023
One way is to make the function ddems nested inside the function idtry and make k a variable in idtry's workspace; then k will be available in ddems's workspace as well because it's a nested function. Then you can loop over the values of k in idtry.
idtry
function idtry
%
rr = 1.3;
tspan = [0:20:40];
%
hold on
k_all = [0.8, 1.6, 2.4, 2.9];
for ii = 1:numel(k_all)
k = k_all(ii);
sol = dde23(@ddems,rr,@ddemshist,tspan);
time = sol.x;
% SD = sol.y(1,:);
ID = sol.y(2,:);
% VD = sol.y(3,:);
% hold on
% plot(time,SD,'b','LineWidth',2) % why plot these at all? they're just going to
% plot(time,VD,'g','LineWidth',2) % be replaced by the next plot() after "hold off"
% hold off
plot(time,ID,'--','LineWidth',2,'DisplayName',sprintf('I_d k=%.1f',k));
end
xlabel('Time(days)');
ylabel('Infected Dogs Population');
% legend('I_d')
legend()
grid on
grid minor
function s = ddemshist(t)
% Constant history function for DDEX1.
s = [40 0 0]';
end
% --------------------------------------------------------------------------
function dydt = ddems(t,y,Z)
Ad = 15; mud = 0.2; %k = 2.9;
cd = 0.01;
Bd = 0.4; r = 0.2; md = 0.02;
% Differential equations function for DDEX1.
ylag1 = Z(:,1);
dydt = [ Ad-Bd*y(1)*ylag1(1)*exp(-mud*r)-(mud+k)*y(1)+cd*y(3)
Bd*y(1)*ylag1(1)*exp(-mud*r)-(mud+md)*y(2)
k*y(1)-(cd+mud)*y(3)
];
end
end
  15 Comments
Voss
Voss on 18 Feb 2023
Edited: Voss on 18 Feb 2023
If the two r's are the same, then remove the one defined in ddems and just use the one defined in idtry/ihplot. Loop over r values in idtry/ihplot, like you did with k and ah.

Sign in to comment.

More Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!