how to Plot improved Euler's Method
2 views (last 30 days)
Show older comments
Dina Abd Elkader
on 31 Mar 2021
Commented: Dina Abd Elkader
on 5 Apr 2021
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 Comment
William
on 31 Mar 2021
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');
Accepted Answer
Reshma Nerella
on 5 Apr 2021
Edited: Reshma Nerella
on 5 Apr 2021
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!
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!