Home > Mobile >  Plot Population growth function with different values of b using for loop in Matlab
Plot Population growth function with different values of b using for loop in Matlab

Time:02-02

I need to plot population growth model with different values of b where b>d and b=d using for loops. Both results should be visible on the same graph with different colors. Here is my function and intial value, but I am not getting how to get the plot .

    [T,Y]=ode45(H,[0:1:time],[N0]);

    Intitial value 
   b= 0.1 0.001
   d=0.001
   N0=400````

I need two line for each b on the same plot.
```***
    Intitial value 
    b= 0.1 0.001;
    d=0.001;
    N0=400;

    H=@(t,N)[b*N-d*N];
    [T,Y]=ode45(H,[0:1:time],[N0]);

    plot(T,Y)
***```

CodePudding user response:

First, you need to put the code in a proper format, now you copied the initial value block twice (I guess you had some issue putting the code format. I hope you can focus on that when asking new questions.

The current code gives an error on the definition of b as you did not define it as a vector. To have two lines, it is best to store the output Y as a matrix of two columns (each column being one vector). MATLAB then outputs each column as a line in the plot.

The following code solves your issue:

% Initial value
b = [0.1, 0.001];
d = 0.001;
N0= 400;
simTime = 0:1:300;

% Preallocate output for the loop
Y = zeros(length(simTime), length(b));

% Run for loop
for i = 1:length(b)
    b_i = b(i);
    H=@(t,N)[b_i*N-d*N];
    [T,y]=ode45(H, simTime, [N0]);
    Y(:,i) = y;
end

% Plot output
plot(T,Y)
  • Related