You are on page 1of 1

Matlab code​

1 clear all​
2 close all​
3 f=@(t,x) 2*x-x.^2;​
4 T=10;​
5 n=20;​
6 dt=T/n;​
7 tspan=0:dt:T;​
8 x=zeros(1,n+1);​
9 x(1)=1; % initial condition​
10 x2=x; % for modified Euler method​
11
12 % solve by Euler method​
13 for i=1:n​
14 x(i+1)=x(i)+dt*f(tspan(i),x(i));​
15 end​
16 plot(tspan,x,'bo-')​
17 hold on​
18
19 % true solution​
20 tt=0:0.01:T;​
21 xt=2./(1+exp(-2*tt));​
22 plot(tt,xt,'r-')​
23
24 % solve by the modified Euler method​
25 for i=1:n​
26 x2(i+1)=x2(i)+dt*f(tspan(i),x2(i));​
27 x2(i+1)=x2(i)+dt/2*(f(tspan(i),x2(i))+f(tspan(i+1),x2(i+1)));​
28 end​
29 plot(tspan,x2,'g*-')​
30 hold on​
31
32
33 % solve by the MATLAB solver ode45​
34 [t3,x3]=ode45(f,[0 T],x(1));​
35 plot(t3,x3,'k+')​
36 plot(t3,zeros(size(t3)),'+')​
37 hold off​
38
39 legend('Euler','Exact','Modified Euler','ode45')​

You might also like