function [Q,R] = mgs(A) % function [Q,R] = mgs(A) % % Math 5334, Fall 2009, HW5 % Trefethen & Bau problem 8.2 % 10/22/2009 VEH % % Computes a reduced QR factorization of A using modified Gram-Schmidt. % A is mxn (m >=n) % Q is mxn with ON columns % R is nxn upper triangular % % Note that any comments I put like this at the beginning of a function % appear when I use help in MATLAB. Type "help mgs" in MATLAB to see. % Get the dimensions of A and initialize Q and R to be zero matrices of the % correct sizes. [m,n] = size(A); R = zeros(n,n); Q = zeros(m,n); if n > m disp('Error: Input matrix must be m x n with m >= n.') disp(sprintf('Given matrix has m = %g and n = %g', m, n)); return; end % No need to loop over the columns when I can just set V to be A. % Then the columns of V are my v_i vectors V = A; for i = 1:n R(i,i) = norm(V(:,i)); Q(:,i) = V(:,i) / R(i,i); % Note that Q(:,i) is MATLAB shorthand for Q(1:m,i); % it means "all rows and column i" for j = i+1:n R(i,j) = Q(:,i)'*V(:,j); V(:,j) = V(:,j) - R(i,j)*Q(:,i); end end