how to Plot improved Euler's Method

2 次查看(过去 30 天)
I am trying to plot Improved Euler's method but I only get an empty graph. I have no idea what is wrong. Here is my code.
fprintf('Imp Euler With h=0.1')
dy=@(x,y) (x+y-1)^2;
f=@(x,y)(tan(x+(pi/4))-x+1);
x0=0;
h=0.1;
xn=0.5;
y=2;
fprintf('x y(Imp. Euler) y(Actual) \n')
fprintf('%f\t %f\t %f\t \n',x0,y,f(x0));
for x=x0:h:xn-h
i1=dy(x,y);
i2=dy(x+h,y+(h*i1));
y = y + (h*((i1+i2)/2));
x=x+h;
fprintf('%f\t %f\t %f\t \n',x,y,f(x));
end
plot(x,y,'r','linewidth',2);
hold on
legend ('Improved Euler')
  1 个评论
William
William 2021-3-31
Hello,
The problem is that you need an array of points to plot a graph. I your code, x is an array but y is a scalar. Try this:
fprintf('Imp Euler With h=0.1')
dy=@(x,y) (x+y-1)^2;
f=@(x,y)(tan(x+(pi/4))-x+1);
x0=0;
h=0.1;
xn=0.5;
fprintf('x y(Imp. Euler) y(Actual) \n')
fprintf('%f\t %f\t %f\t \n',x0,y,f(x0));
x = x0:h:xn;
n = length(x);
y = zeros(1,n);
y(1) = 2;
for j = 1:n-1
i1=dy(x(j),y(j));
i2=dy(x(j+1),y(j)+(h*i1));
y(j+1) = y(j) + (h*((i1+i2)/2));
fprintf('%f\t %f\t %f\t \n',x(j),y(j),f(x));
end
plot(x,y,'r','linewidth',2);
hold on
legend ('Improved Euler');

请先登录,再进行评论。

采纳的回答

Reshma Nerella
Reshma Nerella 2021-4-5
编辑:Reshma Nerella 2021-4-5
Hi,
When you try to plot a line with scalar inputs, the plot doesn't show up in the figure unless you use a Marker like *, +, . etc
In this line of code
plot(x,y,'r','linewidth',2);
x, y are scalars. Since you didn't specify any Marker, you got an empty figure.
Instead try
plot(x,y,'r*','linewidth',2);
Hope this helps!
  1 个评论
Dina Abd Elkader
Dina Abd Elkader 2021-4-5
Unfortunately the problem is still the same. The code generates correct approximation values, and an empty graph. Also I have no idea how to plot the absolute error (AR).

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Mathematics 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by