How to Solve equation using Eulers method in Matlab?

조회 수: 13 (최근 30일)
Samson David Puthenpeedika
Samson David Puthenpeedika 2021년 11월 14일
댓글: Alan Stevens 2021년 11월 14일
Question is as follows:-
Solve the following initial value problem over the interval from t = 0 to 1 where y(0) = 1.
dy/dt = yt^2 - 1.1y
• (a) analytically (showing the intermediate steps in the comments),
• (b) using the explicit Euler’s method with h = 0:5,
• (c) using the explicit Euler’s method with h = 0:25
Note: The Symbolic Math Toolbox should NOT be used.
Below is my code . I wanted to know my mistake if any.
%for h=0.5
h=0.5;
t=0:h:1;
y=zeros(size(t));
y(1)=1;
n=numel(y);
for i = 1:n-1
dydt= (y(i)*t(i).^2)-(1.1*y(i))
y(i+1) = y(i)+(dydt*h)
disp(y(i));
end
dydt = -1.1000
y = 1×3
1.0000 0.4500 0
1
dydt = -0.3825
y = 1×3
1.0000 0.4500 0.2587
0.4500
%for h=0.25
h1=0.25;
t1=0:h1:1;
y1=zeros(size(t1));
y1(1)=1;
n1=numel(y1)
n1 = 5
for i = 1:n1-1
dydt1= (y1(i)*t1(i).^2)-(1.1*y1(i))
y1(i+1)=y1(i)+(dydt1*h1)
disp(y1(i));
end
dydt1 = -1.1000
y1 = 1×5
1.0000 0.7250 0 0 0
1
dydt1 = -0.7522
y1 = 1×5
1.0000 0.7250 0.5370 0 0
0.7250
dydt1 = -0.4564
y1 = 1×5
1.0000 0.7250 0.5370 0.4229 0
0.5370
dydt1 = -0.2273
y1 = 1×5
1.0000 0.7250 0.5370 0.4229 0.3660
0.4229
Display in a plot
• the analytical result (a) as a black solid line, and
• the numerical results (b - c) as solid lines with point markers in different color
• with the corresponding labels of the axes and legend.
% analytical sol(plz check for this too)
T=[0 1]
T = 1×2
0 1
Y=[1 -0.766]
Y = 1×2
1.0000 -0.7660
% Graph
plot(t,y,'r',"DisplayName","h=0.5");
hold on
plot(t1,y1,'b',"DisplayName","h=0.25");
plot(T,Y,'k',"DisplayName","Anlaytical sol");
legend
grid on;

채택된 답변

Alan Stevens
Alan Stevens 2021년 11월 14일
Here's part (a) for you - definitely not a straight line!

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by