how to Plot improved Euler's Method
Show older comments
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
More Answers (0)
Categories
Find more on Mathematics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!