function Xvec = forwardSubstitutionR(LOWER,Bvec,n)
% Solving a lower triangular system LOWER Xvec = Bvec by forward-substitution.
% Input matrix LOWER is an n by n lower 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
% This version uses row processing (good for C or C++).
% K. Ming Leung, 02/13/04, 02/16/05 (using better variable names)

Xvec = zeros(n,1); % initialization for efficiency purpose only
for k = 1:n
    if (LOWER(k,k)==0) error('Matrix is singular!'); end;
    % Row processing: involves the jth row of L
    % to the left of the main diagonal.
    j = 1:k-1; 
    Xvec(k) = (Bvec(k)-LOWER(k,j)*Xvec(j))/LOWER(k,k);  % involves a dot-product
end       
