%  Square-wave test for the Lax method to solve the advection equation
clear;

% Parameters to define the advection equation and the range in space and time
Lmax = 1.0; 	% Maximum length
Tmax = 1.;    	% Maximum time
c = 1.0;    	% Advection velocity

%  Parameters needed to implement the Lax method
Nt = 200;           % Number of time steps
Dt = Tmax/Nt;       % Time step	
Nx = 300;			% Number of space steps
Dx = Lmax/Nx;		% Space step	
b = c*Dt/(2.*Dx);   % beta parameter in the finite-difference implementation

% Remember that the Lax method is stable for b=< 1/2 but it gets difussed unless abs(b)= 1/2


%  Initial condition: the initial value of the u function (amplitude of the wave initially)

Nfront=round(Nx/2); % The wave-front: intermediate point from which u=0

for i = 1:(Nx+1)
   if i < Nfront
      u(i,1)=1.;
   else
      u(i,1)=0.;
   end 
   x(i) =(i-1)*Dx;  % We also define vector x, due to the space discretization
end



%  Boundary conditions: value of the the u function at the boundaries at any time 
for k=1:Nt+1
        u(1,k) = 1.;
        u(Nx+1,k) = 0.;
        t(k) = (k-1)*Dt; % We also define vector t, due to the time discretization
end


%  Implementation of the Lax method
for k=1:Nt          %  Time loop
   for i=2:Nx		%  Space loop
      u(i,k+1) =0.5*(u(i+1,k)+u(i-1,k))+b*(u(i+1,k)-u(i-1,k));
   end
end

% Graphical representations of the evolution of the wave
plot(x,u(:,1),'-b',x,u(:,round(Nt/10)),'--g',x,u(:,round(Nt/3)),':b',x,u(:,Nt),'-.r')
title('Square-wave test within the Lax Method')
xlabel('X')
ylabel('Amplitude(X)')
