r = 2;
K = 1000;
f = @(t,x) r.*x.*(1-x./K);
fx = @(t,x) r-(2.*r.*x)./K;
dt = 0.1;
t = 0:dt:10;
x = zeros(size(t));
x(1) = 1;
eps = 100*ones(size(t));
for i = 1:length(t)-1
x(i+1) = x(i)+dt*f(t(i),x(i))+0.5*dt^2*(fx(t(i),x(i))*f(t(i),x(i)));
end
plot(t,x,’m.-‘)
xlabel(‘Time’)
ylabel(‘Population’)
g = @(tau) spline(t,x,tau);
g500 = @(tau) spline(t,x,tau)-500;
g900 = @(tau) spline(t,x,tau)-900;
t_500 = mean(fsolve(g500,[0,10]));
t_900 = mean(fsolve(g900,[0,10]));
hold on
plot([t_500 t_500],[0 g(t_500)],’c–‘)
plot([0 t_500],[g(t_500) g(t_500)],’c–‘)
hold off
hold on
plot([t_900 t_900],[0 g(t_900)],’c–‘)
plot([0 t_900],[g(t_900) g(t_900)],’c–‘)
hold off