function multistep_zero_stability_demo

f = @(t,x) -2*x; % x'(t) = x
xex = @(t) exp(-2*t);

tspan = [0 2]; % integrate from t=0 to t=10

x0 = 1; % start with x(0) = 1

%%
h = 2^(-2); % time step
[t,x] = method1(f, tspan, x0, h); %
plot(t,x,'b.-','markersize',15,'linewidth',2,'DisplayName','Method 1') % plot output
hold on

[t,x] = method2(f, tspan, x0, h); %
plot(t,x,'r.-','markersize',15,'linewidth',2,'DisplayName','Method 2') % plot output

plot(t,xex(t),'g--','markersize',15,'linewidth',2,'DisplayName','Exact') % plot output
grid on
legend show
set(gca,'fontsize',15)



function [t,x] = method1(f, tspan, x0, h)

t0 = tspan(1); 
tfinal = tspan(end);

% set up the t values at which we will approximate the solution
t = [t0:h:tfinal];

% include tfinal even if h does not evenly divide tfinal-t0
if abs(t(end)-tfinal)>1e-8
    t = [t tfinal];
end

x = [x0 zeros(length(x0),length(t)-1)];
for j=1:length(t)-1    
    if j < 2
        x(:,1) = 1;
        x(:,2) = 1.01*exp(-2*h);  % introduce 1% error in initial condition
    else
        x(:,j+1) = x(:,j) + .5*h*(3*(-2*x(:,j))-(-2*x(:,j-1)));
    end    
end


function [t,x] = method2(f, tspan, x0, h)

t0 = tspan(1); tfinal = tspan(end);

% set up the t values at which we will approximate the solution
t = [t0:h:tfinal];

% include tfinal even if h does not evenly divide tfinal-t0
if abs(t(end)-tfinal)>1e-8
    t = [t tfinal];
end

x = [x0 zeros(length(x0),length(t)-1)];
for j=1:length(t)-1
    k1 = feval(f,t(j),x(:,j));
    if j < 2
        x(:,1) = 1;
        x(:,2) = 1.01*exp(-2*h);  % introduce 1% error in initial condition
    else
        x(:,j+1) = x(:,j-1) + 2*h*k1;
    end
    k2 = k1;
end
