% % Matlab function mgs.m % % Purpose: This function uses the modified Gram-Schmidt % orthonormalization algorithm to compute the % reduced QR factorization of the matrix A. If % the matrix does not possess linearly independent % columns, then this algorithm will trap the error % and return to the calling environment. Also, the % function will print a diagnostic that measures the % orthonormality of the Q matrix. % % Author: % Copyright (c)2001 by John S. Tamaresis. % All rights reserved. % % Date: % 27 February 2001 % % Inputs: % A = m-by-n matrix with real entries (m >= n) % % Outputs: % Q = m-by-n matrix with orthonormal columns % R = n-by-n upper triangular matrix % function [Q,R] = mgs(A) % Determine the size and condition number of the matrix. [mrows,ncols] = size(A); if mrows < ncols error('invalid dimension for A') end % Initialize the factor matrices. Q = zeros(mrows,ncols); R = zeros(ncols); % Begin the factorization. for ic=1:ncols, R(ic,ic) = norm(A(:,ic)); % Test the current diagonal entry to determine % whether the matrix A is rank deficient. if R(ic,ic) == 0. error('The original matrix is rank deficient.') end Q(:,ic) = (1./R(ic,ic)).*A(:,ic); for ir=ic+1:ncols, R(ic,ir) = (Q(:,ic)')*A(:,ir); A(:,ir) = A(:,ir) - R(ic,ir)*Q(:,ic); end end % End of function