Improve Mathworks Euler method

조회 수: 1 (최근 30일)
Karol T
Karol T 2021년 4월 24일
편집: Karol T 2021년 4월 25일
Hi, I'm newbi to MATLAB, but I am writing code based on this example: https://www.mathworks.com/matlabcentral/fileexchange/72522-euler-method. I wrote code that is compiled and there is output on it but I don't know how to check it properly. I would be very grateful if someone would take a look.

답변 (1개)

Alan Stevens
Alan Stevens 2021년 4월 25일
The method is ok, though could be more streamlined, for example:
f1=@(x) 5*x+50;
f2 =@(x,y) x*10 +10*y;
x1=0;
y1=0;
x2=0;
y2= 0;
xn=10;
h=0.2;
n = round(xn/h);
for i = 1:n
y1=y1+h*f1(x1);
x1=x1+h;
y2=y2+h*f2(x2,y2);
x2=x2+h;
end
fprintf('\n x1 y1 x2 y2 ');
fprintf('\n%4.3f %4.3f %4.3f %4.3f ',x1,y1,x2,y2);
Your functions (especially f2) show up the deficiencies in the Euler method (the true final value at x = 10, for f1 is 750, and for f2 is ~2.688*10^42).
  댓글 수: 2
Alan Stevens
Alan Stevens 2021년 4월 25일
More like this (note: I altered your value of D to give more reasonable results):
A = 5;
B = 50;
C = 0.1;
D=1;
f1=@(x) (1./D)*x;
f2 =@(x,y) (1./D)*(A-(B*x)-y);
x1(1)=0;
y1(1)=0;
x2(1)=0;
y2(1)= 0;
xn=10;
h=0.2;
n = round(xn/h);
for i = 1:n-1
y1(i+1)=y1(i)+h*f1(x1(i));
x1(i+1)=x1(i)+h;
y2(i+1)=y2(i)+h*f2(x2(i),y2(i));
x2(i+1)=x2(i)+h;
end
fprintf('\n x1 y1 x2 y2 ');
x1 y1 x2 y2
fprintf('\n%4.3f %4.3f %4.3f %4.3f ',x1(end),y1(end),x2(end),y2(end));
9.800 47.040 9.800 -435.001
figure(1);
plot(x1,y1), grid
figure(2)
plot(x2,y2),grid
Alan Stevens
Alan Stevens 2021년 4월 25일
Yes, they will both appear on one graph that way.

댓글을 달려면 로그인하십시오.

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by