
#sparse matrices - 3 diag matrix
1==1;

function L=lap1s(n)
#creates sparse discrete minus 1d laplacian on
#uniform grid scaled by h^2 i.e. 3 diag matrix with 
#2 on the main diag, -1 on 1st super and sub diagonals
#n size of L nxn\
#OUTPUT 
#L 3diag matrix
#
#Example: L=lap1s(4); full(L) 
 S=-ones(1,3*n-2);
 S(1:n)*=-2;
 I=[1:n,1:n-1,2:n];#row indices: diagonal; superdiag and subdiag
 J=[1:n,2:n,1:n-1];#column indices: diagonal; superdiag and subdiag
 L=sparse(I,J,S,n,n);
endfunction


function L1=lap1(n)
#creates s discrete minus 1d laplacian on
#uniform grid scaled by h^2 i.e. 3 diag matrix with 
#2 on the main diag, -1 on 1st super and sub diagonals
#in diagonal format (using diag())
#n size of L nxn\
#OUTPUT 
#L1 3diag matrix
#
#Example: L1=lap1(4); full(L) 
 L1=diag(2*ones(1,n))-diag(ones(1,n-1),1)-diag(ones(1,n-1),-1);
endfunction



function L2=lap1l(n)
#creates s discrete minus 1d laplacian on
#uniform grid scaled by h^2 i.e. 3 diag matrix with 
#2 on the main diag, -1 on 1st super and sub diagonals
# (using loop)
#n size of L nxn\
#OUTPUT 
#L2 3diag matrix
#
#Example: L2=lap1l(4); full(L) 
 L2=zeros(n,n); #measure the time  with this line commented out
 for k=1:n-1,
  L2(k:k+1,k:k+1)=[2 -1;-1 2];
 endfor
endfunction

#we check the time
M=3;
N=10;
crt=sol=zeros(M,4);
for k=1:M,
 tic;L=lap1s(N);tcs=toc;
 tic;L1=lap1(N);tcd=toc;
 tic;L2=lap1l(N);tcl=toc;
 crt(k,:)=[N,tcs,tcd,tcl];
 f=randn(N,1);
 tic;x=L\f;tss=toc;
 tic;x1=L1\f;tsd=toc;
 tic;x2=L2\f;tsl=toc;
 sol(k,:)=[N,tss,tsd,tsl];
 [norm(x-x1),norm(x-x2)]
 N*=10;
endfor
crt #times of creating the matrix
sol #times of solving
#N=1e4 - we can create matrices but solvers failed i.e. it takes too long...
 tic;L=lap1s(N);tcs=toc;
 tic;L1=lap1(N);tcd=toc;
 tic;L2=lap1l(N);tcl=toc;
 crt(M+1,:)=[N,tcs,tcd,tcl]
#for N=1e5 the other matrices exhaust memory

sol=sol(:,1:2);
crt=crt(:,1:2);
for k=M+1:M+4,
 tic;L=lap1s(N);ct=toc;
# tic;L1=lap1(N);toc 
# tic;L2=lap1l(N);toc
crt(k,:)=[N,ct];
f=randn(N,1);
tic;x=L\f;st=toc;
sol(k,:)=[N,st];
N*=10;
endfor
crt
sol
#check the last rows - solving was faster than creation of the matrix
#try larger N e.g. 1e8...
