首页 > 代码库 > Gram Shimidt QR Factorization Matlab version

Gram Shimidt QR Factorization Matlab version

function [Q,R] = gram_schmidt_qr(A)

% Formation: A = QR
% The implementation of QR Factorization(classical Gram-Schmidt method)
% Q is orthonormal basis for R(A)
% R is an upper-triangular matrix with positive diagonal entries.

% Author: Zhenlin Du(Johnsondu)
% Email:  qlduzhlin@126.com
% Time:   2014-11-27 22:00

A = double(A)
[m, n] = size(A);
Q = zeros(m, n);
R = zeros(n, n);

% for k = 1
u1 = A(:, 1);
Q(:, 1) = u1 / (sqrt(dot(u1, u1)));
R(1, 1) = (sqrt(dot(u1, u1)));

% for k > 1
for i = 2 : n
	% take column i
	u = A(:, i);  
	
    % compute R and u
	for j = 1: i - 1
		R(j, i) = dot(Q(:, j), u);
		u = u - R(j, i) * Q(:, j);
    end
    
    % get R(i, i)
	R(i, i) = (sqrt(dot(u, u)));
    % normalize
	u = u / R(i, i);
	Q(:, i) = u;
end

Gram Shimidt QR Factorization Matlab version