-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ask2.m
39 lines (39 loc) · 1005 Bytes
/
Ask2.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
% Second Script
% Numerical solve of ordinary differental equation
% with the method of Euler, the improved method and the modified
% We have the problem
h = 0.1;
x = 0:h:3;
n = length(x);
y = exp(x) - x - 1;
y0 = 0;
f = @(x,y) x + y ;
% Euler Method
yE = zeros(size(x),1);
yE(1) = y0;
for( i = 1:n-1)
yE(i+1) = yE(i) + h.*f(x(i),y(i));
end
% Modified Euler Method
yM = zeros(size(x),1);
yM(1)= y0;
for ( i = 1:n-1 )
yM(i+1) = yM(i) + h.* f(x(i) + h/2, y(i) + h/2.*f(x(i),y(i)));
end
% Improved Euler Method
yI = zeros(size(x),1);
yI(1) = y0;
for ( i = 1:n-1 )
yI(i+1) = yI(i) + h/2.*(f(x(i),y(i)) + f(x(i) + h, y(i) + h.*f(x(i),y(i))));
end
% Graph of solutions
figure();
plot(x, y, 'b-');
xlabel('x','fontsize',16);
ylabel('y(x)','fontsize',16);
hold on
plot(x,yE,'r*');
plot(x,yM,'k+');
plot(x,yI,'gx');
legend('Analytic Solution','Euler Method Solution','Modified Euler Method Solution','Improved Euler Method Solution','Location','northwest');
hold off