  function [w,err,its] = StatVec(P,v,tol,kMax)
% P is an n-by-n array of transition probabilities
% v is an n-by-1 state vector
% Iterates until there is the changes in the state vector
% are less than tol where tol is a small positive tolerance.
% A maximum of kMax iterations are performed.
% w is the approximate stationary vector and err is an estimate of
% the error in its components.

  k = 0;   % iteration counter
  while k==0 || (k<kMax && err>tol)
      % Save the old state vector..
      w = v;
      % Get the next one...
      v = Update(P,w);
      k = k+1;
      err = max(abs(w-v));
      error(k) = err;
  end
  its = k;
  semilogy(1:k,error)
  xlabel('Iteration','FontSize',14);
  ylabel('Error','FontSize',14)
  shg