%
%  Solve 1D hyperbolic problem
%
%      u_t + a*u_x = b*u, 0<x<L, a>0
%      u(0,t)=0, t>0
%      u(x,0)=u0(x)
%
%      n = number of spatial grid points: h=L/(n-1)
%      m = number of time steps: dt=T/m
%
function hyp1(a,b,n,m)
if a <= 0
    fprintf(1,'Coefficient "a" should be positive\n');
    return;
end
L=2;
T=2;
dt=T/m;
x=L*(0:n-1)/(n-1);
h=L/(n-1);
c1 = dt*a/h;
c2 = dt*b;
u=u0(x);
unew=zeros(n,1);
fprintf(1,'h=%.2f, dt=%.2f, Courant number = %.3f\n',h,dt,dt*(a-b*h)/h);   
for step=1:m
    %
    % Backward difference method
    %
    for j=2:n
        unew(j) = u(j) - c1*(u(j)-u(j-1)) + c2*u(j);
    end
    t = step*dt;
    uexact = exp(b*t)*u0(x-a*t); 
    if mod(step,1)==0
        plot(x,unew,x,uexact,'LineWidth',2); axis([0 L -0.1 1]);
        str = sprintf('time = %f',t);
        title(str);
        pause(0.5);
    end
    u=unew;
end

%
% Initial value
%
function u=u0(x)
u=(x>=0.25 & x<=0.75).*cos(2*pi*(x-0.5)).^2;

