
clear all;
1==1;

%sparse matrix

%def sparse matrix convert it back to full format (any 2x2
A=[2 1 ;3 4]
B=sparse(A)
A-full(A)

%tridiagonal with 3 on main diag and -1 on upper and lower diagonals

%with a loop

function A=threediag1(N)
  for k=1:N-1,
    A(k:k+1,k:k+1)=[2 -1;-1 2];
  end
end

function A=threediag2(N)
 on=ones(N,1);  
 A=2*diag(on)-diag(on(1:N-1),1) -diag(on(1:N-1),-1); 
end
N=10;
for k=1:4,
 NN(k)=N; 
 tic;A=threediag1(N);t1(k)=toc;
 tic;A=threediag2(N);t2(k)=toc;
 N*=5;
end
 [NN;t1;t2]'
 
%we can improve loop function 
function A=threediag3(N)
  A=zeros(N,N);
  for k=1:N-1,
    A(k:k+1,k:k+1)=[2 -1;-1 2];
  end
end
N=10;
for k=1:4,
 NN(k)=N; 
 tic;A=threediag3(N);t3(k)=toc;
 N*=5;
end
 [NN;t1;t2;t3]'
 
 %create this matrix in a sprse format using sparse(diag(..)   )
 %and sparse(I,J,S,N,N) -c compare time
 
function A=threesp1(N)
  I=[1:N,1:N-1,2:N];
  J=[1:N,2:N,1:N-1];
  S=[2*ones(1,N),-ones(1,2*N-2)];
  A=sparse(I,J,S,N,N);
end

function A=threesp2(N)
 on=ones(N,1);  
 A=sparse(2*diag(on)-diag(on(1:N-1),1) -diag(on(1:N-1),-1)); 
end
 
 N=10;
for k=1:4,
 NN(k)=N; 
 tic;A=threesp1(N);t1(k)=toc;
 tic;A=threesp2(N);t2(k)=toc;
 N*=10;
end
disp("creating sparse format of 3diag mat");
 [NN;t1;t2]'
 
 
 %compare efficiency of sparse vs standard solver
 
 N=10;M=4;
 NN=t1=t2=zeros(M,1);
 for k=1:M,
   NN(k)=N;
   A1=threediag3(N); %full format
   A2=sparse(A1);
   f=randn(N,1);
   tic;A1\f;t1(k)=toc;
   tic;A2\f;t2(k)=toc;
   N*=5;
 end
 disp('sparse vs full solvr for tridiagonal matrix')
[NN,t1,t2] 


%integration
%simple integrals
disp('simple integrals')
quad(@sin,0,1) +cos(1)-cos(0)
quad(@(x)exp(-0.5*x*x),-inf,inf)-sqrt(2*pi)
quad(@(x) x.*x,0,1) - 1/3
%less smotth integrands

p=0.5;quad(@(x) abs(x)^p,0,1) - 2/3
%compare time
p=2;tic;quad(@(x) abs(x)^p,0,1);toc
p=0.5;tic;quad(@(x) abs(x)^p,0,1);toc


%implement the function F(x)=1/sqrt(2*pi)*\int_{-inf}^x exp(-0.5*t*t) dt

function y=dystN(x)
  y=quadcc(@(x)exp(-0.5*x.*x),-inf,x)/sqrt(2*pi);
end  