function Xvec = backSubstitution(UPPER,Bvec,n)
% Solving an upper triangular system by back-substitution
% U x = b
% This version accesses the matrix by columns.
% Input matrix UPPER is an n by n upper triangular matrix
% Input vector Bvec is n by 1
% Input scalar n specifies the dimensions of the arrays
% Output vector Xvec is the solution to the linear system

% K. Ming Leung, 02/15/05

Xvec = zeros(n,1);
for j = n:-1:1
    if (U(j,j)==0) error('Matrix is singular!'); end;
    Vec(j) = Bvec(j)/UPPER(j,j);
    i = 1:j-1;
    Bvec(i) = Bvec(i)-UPPER(i,j)*Xvec(j);
end


        
