Plot function for different values of two coupled variables

3 Ansichten (letzte 30 Tage)
Sophia
Sophia am 4 Mär. 2025
Kommentiert: Voss am 5 Mär. 2025
Hi all, I'm new to matlab so sorry if this is trivial. I'm trying to run the following code for three different values of variables k5 and k6. The thing is, I don't want a plot for every possible combination of k5 and k6. I only want three different specific combinations of k5 and k6: k5=0.1 AND k6=0.3, k5=0.2 AND k6=0.5, and k5=0.3 AND k6=0.7. So I want to run the for loop I've written for each of those three conditions. I should end up with a graph containing 6 lines (p and m vs time for each of the three conditions). I could hard code this in three different for loops but I'd rather do something nicer (unless that's not possible).
Here's the code:
k4=0.15;
a0=15;
p0=0;
m0=0;
dt=1/60;
T=60;
time=[0:dt:T];
N=length(time);
p=zeros(1,N); %placeholder output vector
p(1)=p0; %initial condition
m=zeros(1,N); %placeholder output vector
m(1)=m0; %initial condition
for n=1:N-1
dmdt=a0-k4*m(n);
dm=dmdt*dt;
m(n+1)=m(n)+dm;
dpdt=k5*m(n)-k6*p(n);
dp=dpdt*dt;
p(n+1)=p(n)+dp;
plot(time,m)
plot(time,p)
end

Akzeptierte Antwort

Voss
Voss am 4 Mär. 2025
k4=0.15;
a0=15;
p0=0;
m0=0;
dt=1/60;
T=60;
time=0:dt:T;
N=length(time);
p=zeros(1,N); %placeholder output vector
m=zeros(1,N); %placeholder output vector
figure
hold on
all_k5 = [0.1 0.2 0.3];
all_k6 = [0.3 0.5 0.7];
for ii = 1:numel(all_k5)
k5 = all_k5(ii);
k6 = all_k6(ii);
p(1)=p0; %initial condition
m(1)=m0; %initial condition
for n=1:N-1
dmdt=a0-k4*m(n);
dm=dmdt*dt;
m(n+1)=m(n)+dm;
dpdt=k5*m(n)-k6*p(n);
dp=dpdt*dt;
p(n+1)=p(n)+dp;
end
plot(time,m,'DisplayName',sprintf('%s [k_5=%g, k_6=%g]','m',k5,k6))
plot(time,p,'DisplayName',sprintf('%s [k_5=%g, k_6=%g]','p',k5,k6))
end
legend('FontName','Courier')
The m vectors are the same for each ii, since m doesn't depend on k5 or k6. Therefore all 3 m lines coincide.

Weitere Antworten (1)

Torsten
Torsten am 4 Mär. 2025
Bearbeitet: Torsten am 4 Mär. 2025
k5 = [0.1 0.2 0.3];
k6 = [0.3 0.5 0.7];
colors = ['b','r','g'];
N = 3;
hold on
for i = 1:N
[time,p,m] = fun(k5(i),k6(i));
plot(time,[p;m],colors(i))
end
hold off
grid on
function [time,p,m] = fun(k5,k6)
k4=0.15;
a0=15;
p0=0;
m0=0;
dt=1/60;
T=60;
time=[0:dt:T];
N=length(time);
p=zeros(1,N); %placeholder output vector
p(1)=p0; %initial condition
m=zeros(1,N); %placeholder output vector
m(1)=m0; %initial condition
for n=1:N-1
dmdt=a0-k4*m(n);
dm=dmdt*dt;
m(n+1)=m(n)+dm;
dpdt=k5*m(n)-k6*p(n);
dp=dpdt*dt;
p(n+1)=p(n)+dp;
%plot(time,m)
%plot(time,p)
end
end

Community Treasure Hunt

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

Start Hunting!

Translated by