MATLAB Answers

how to Plot improved Euler's Method

22 ビュー (過去 30 日間)
Dina Abd Elkader
Dina Abd Elkader 2021 年 3 月 31 日
コメント済み: Dina Abd Elkader 2021 年 4 月 5 日
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 件)

Community Treasure Hunt

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

Start Hunting!

Translated by