function Xvec = backSubstitutionR(UPPER,Bvec,n)
% Solving an upper triangular system by back-substitution
% U x = b
% This version accesses the matrix by rows.
% 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

% initialize solution vector to 0
Xvec = zeros(n,1);
% loop through equations from the last to the first
for k = n:-1:1
    Cols = k+1:n;   % index vector for the columns within the kth row
    % the '*' here actually performs a dot-product:
    Xvec(k) = (Bvec(k)-UPPER(k,Cols)*Xvec(Cols))/UPPER(k,k);
end


        
