 function [vec, lam, res] = arn0 (A,v,m,gam)
%--------------------------------------------
% function [vec, val, res] = arn0 (A,v,m,gam)
% m steps of the Arnoldi process:
% A   = sparse matrix
% v   = initial vector,
% m   = dimension of Krylov subspace
% gam = seek eigenvalue closest to gam
% return: 
% vec = approximate eigenvector
% val = approximate eigenvalue
% res = residual norm history
 %--------------------------------------------
 n = size(A,1);
%--------------------------------------------
% start procedure
%-------------------------------------------- 
 ro = norm(v,2)  ; 
 t = 1.0/ ro   ;
 V(1:n,1) = v*t; 
%% 
for i=1:m  
  i1 = i + 1  ; 
  V(1:n,i1) = A*V(1:n,i)  ;
%--------------------------------------------
%                 modified GS  ;
%--------------------------------------------
 for j=1:i 
   t = V(1:n,j)'*V(1:n,i1)  ;
   H(j,i) = t  ;
   V(1:n,i1) = V(1:n,i1) - t*V(1:n,j)  ; 
 end  ;
%
 t = norm(V(1:n,i1),2)  ;
 H(i1,i) = t  ;
 if (t  ~= 0.0)  
   t = 1.0 / t  ;
   V(1:n,i1) = V(1:n,i1)*t  ;  
 end  
%--------------------------------------------
% define Arnoldi Objects 
%--------------------------------------------
 Vm = V(1:n,1:i);
 Hm = H(1:i,1:i);
%%%%%%%%%%%%%%%%%%%%%%%%%%%% Pure arnoldi 
 [U,vals] = eig(Hm);
 vals = diag(vals);
 [~,k]  = min(abs(gam - vals));
%%-------------------- record residual norm
 lam = vals(k);
 vec = Vm*U(:,k);
 res(i) = norm(A*vec - lam*vec);
end

