MATLAB: How to use Euler’s method to solve the logistic grown model

differential equationseuler's methodlogistic growthmathode

Hi all,
I need help solving the logistic growth model (an ODE) using Euler's Method in MATLAB.
The function is: (dy/dx) = r*y*(1-(y/K)) where r is the growth rate and K is the carrying capacity.
I have solved this out by hand but I am having a difficult time implementing it as a function.
I'm meant to write a function with two inputs (a vector time, t, and an initial y, y0) and this function is meant to output a vector of solutions to the ode for each time t and plot the results.
I know there is mean to be some h as a time step to evaluate a new tangent line at the function and the smaller that step is, the more accurate the answer is, but I'm having a hard time writing the code.
Can anyone help?

Best Answer

One step of Euler's Method is simply this:
(value at new time) = (value at old time) + (derivative at old time) * time_step
So to put this in a loop, the outline of your program would be as follows assuming y is a scalar:
t = your time vector
y0 = your initial y value
dt = the time step (you write code here to calculate this from the t vector based on your instructions)
y = zeros(size(t)); % allocate a vector to hold the output values, same size as t
y(1) = y0; % the initial value
for k=2:numel(t) % loop to find all the subsequent values y(2) through y(end)
y(k) = y(k-1) + (you write code for derivative dy/dt here) * dt; % The Euler step
end
So, complete the code as indicated above, and then add code to wrap all of this inside a function per the instructions and you will be done. Your function will return the y vector. (Note that t and y0 will be coming in as function arguments, not set directly in the function itself)
Related Question