Improve Mathworks Euler method

8 次查看(过去 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 中查找有关 Numerical Integration and Differential Equations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by