function multistep_cfl_demo

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

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

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

h = .9; % stable time step
[t,x] = AB2(f, tspan, x0, h); % call AB2
hold on
plot(t,x,'-.','markersize',15,'linewidth',2) % plot output

h = 1; % nearly unstable time step
[t,x] = AB2(f, tspan, x0, h); % call AB2
hold on
plot(t,x,':','markersize',15,'linewidth',2) % plot output

h = 1.1; % unstable time step
[t,x] = AB2(f, tspan, x0, h); % call AB2
hold on
plot(t,x,'--','markersize',15,'linewidth',2) % plot output

plot(t,xex(t),'k-','linewidth',2) % plot output

legend('h = .75','h = 1','h = 1.1','Exact')
set(gca,'fontsize',6)

function [t,x] = AB2(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

% execute AB with Heun start
x = [x0 zeros(length(x0),length(t)-1)];
for j = 1:length(t)-1     
    
    k1 = feval(f,t(j),x(:,j)); % single function evaluation    
    
    if j == 1        
        x(:,j+1) = exp(t(j+1));        
    else
        
        x(:,j+1) = x(:,j) + .5*h*(3*k1-k2);
        
    end
    
    k2 = k1;
    
end



