function euler
% euler method for various M values when solving
% y' = ry(1-y) with y(0) = y0 '
% clear all previous variables and plots
clear *
clf
% parameters for calculation
r=10;
y0=0.01;
tmax=1;
% calculate and plot exact solution
tt=linspace(0,tmax,100);
a0=(1-y0)/y0;
for it=1:100
exact(it)=1/(1+a0*exp(-r*tt(it)));
end;
plot(tt,exact,'k','LineWidth',1)
hold on
% label axes
xlabel('t-axis','FontSize',14,'FontWeight','bold')
ylabel('Solution','FontSize',14,'FontWeight','bold')
% insert title
say=['Solving Logistic Equation Using Euler Method'];
title(say,'FontSize',14,'FontWeight','bold')
% have MATLAB use certain plot options (all are optional)
box on
axis([0 1 0 1.05])
set(gca,'ytick',[0 0.2 0.4 0.6 0.8 1.0]);
set(gca,'FontSize',14);
% loop used to increase M value
M=1;
for icounter=1:4
M=M*4
% calculate Euler solution
t=linspace(0,tmax,M+1);
h=t(2)-t(1);
euler=y0;
y=y0;
for i=2:M+1
yy=y+r*h*y*(1-y);
euler=[euler, yy];
y=yy;
end;
% plot solution
if icounter==1
plot(t,euler,'--ro','MarkerSize',7)
legend(' Exact',' Euler (M = 4)',2)
set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold')
pause
elseif icounter==2
plot(t,euler,'--b*','MarkerSize',7)
legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',2)
set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold')
pause
elseif icounter==3
plot(t,euler,'--mo','MarkerSize',7)
legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',' Euler (M = 64)',2)
set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold')
pause
elseif icounter==4
plot(t,euler,'-r','LineWidth',1)
legend(' Exact',' Euler (M = 4)',' Euler (M = 16)',' Euler (M = 64)',' Euler (M = 256)',2)
set(findobj(gcf,'tag','legend'),'FontSize',14,'FontWeight','bold')
end;
end
hold off