How to plot two different step sizes on the same plot
18 views (last 30 days)
Show older comments
I am trying to plot two different values for h ( the step size) for the functions below all on the same plot... I have both functions plotting to the same graph but i can only plot one h at a time.. is there away to have both h's plot? h = .001 and h=.01
clear all, clc
y0 = 1; t0 = 0;
h= 0.01;
tmin= 0;
tmax= 2;
n = (tmax-tmin)/h;
[t,y] = explicit_euler(t0,y0,h,n)
[t,y]=predictor_corrector(t0,y0,h,n)
function F = evalF(t,y)
F = -2*y + t.^2;
end
function [t,y]=predictor_corrector(t0,y0,h,n)
t= zeros(n+1,1);
y= zeros(n+1,1);
t(1) = t0;
y(1) = y0;
for i = 2:n+1
yp = y(i-1) + h*evalF(t(i-1),y(i-1));
yc = y(i-1) + h*evalF(t(i-1)+h,yp);
y(i) = (yp+yc)*0.5;
t(i) = t(i-1) + h;
end
plot(t,y,'b-o')
hold on
end
function [t,y]=explicit_euler(t0,y0,h,n)
% t0 == initial value of t
% y0 == initial value of y
% h step size
% n number of iterations
t = zeros(n+1,1);
y = zeros(n+1,1);
t(1) = t0;
y(1) = y0;
for i = 2:n+1
y(i) = y(i-1) + h*evalF(t(i-1),y(i-1));
t(i) = t(i-1) + h;
end
plot(t,y,'r-o')
hold on
end
0 Comments
Answers (1)
madhan ravi
on 12 Apr 2020
Edited: madhan ravi
on 12 Apr 2020
for h = ...
figure
[t,y] = explicit_euler(t0,y0,h,n)
[t1,y1]=predictor_corrector(t0,y0,h,n)
end
2 Comments
See Also
Categories
Find more on 2-D and 3-D Plots 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!