Improved Eulers Method Loop

조회 수: 1 (최근 30일)
MC
MC 2019년 10월 6일
답변: Sulaymon Eshkabilov 2019년 10월 6일
I would like to use the improved eulers method to graph and solve the IVP y'=cot(y),y(0) = pi/6 using a step size of 1,0.5 and 0.25. My code currently does not generate a plot at I am not sure where there is a logic error. Could anyone point me in the right direction ?
% improved eulers method for stped size 1
y0 = pi/6;
x0 = 0;
xn = 5;
h = 1;
dy = @(x,y) cot(y); % dy/dx
y = y0;
for x = x0+h :h: xn
y1 = y + dy(x,y)*h;
end
plot(x,y1)
legend('Improved Euler 1')
hold on
% Solve the ODE
f = @(t,y) cot(y);
y0 = pi/6;
t2 = 0:1:5;
[t2,y2] = ode45(f,[0 5],y0);
plot(t2,y2,'LineWidth',3,'DisplayName','Exact solution');
legend show
Thanks,
MC

답변 (1개)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2019년 10월 6일
Hi,
You have overlooked the loop iteration and time space. Here is the corrected code:
% improved eulers method for stped size 1
y0 = pi/6;
x0 = 0;
xn = 5;
h = 1; % h = 0.5; % h = 0.25;
dy = @(x,y) cot(y); % dy/dx
y = y0;
x = x0:h:xn;
for ii = 1:numel(x)-1
y(ii+1) = y(ii) + dy(x(ii),y(ii))*h;
end
plot(x,y, 'b-o')
legend('Improved Euler 1')
hold on
% Solve the ODE
f = @(t,y) cot(y);
y0 = pi/6;
t2 = 0:h:5;
[t2,y2] = ode45(f,t2,y0);
plot(t2,y2,'LineWidth',3,'DisplayName','Exact solution');
legend show
%%
Now you can extent the code with other time steps for h= 0.5 and 0.25 by changing the value of h.
Good luck.

카테고리

Help CenterFile Exchange에서 Ordinary Differential Equations에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by