% qr_givems.m -- Compute QR decomposition using Givens rotations
% Written Fall 2005 by Eric Olson for Math 466/666
%
% [Q,R]=qr_givens(A);

function [Q,R]=qr_givens(A)
    zero=max(max(abs(A)))*1E-14;
    n=rows(A);
    m=columns(A);
    Q=eye(n);
    R=A;
    for j=1:m
        for k=n-1:-1:j
            r=norm(R(k:k+1,j));
            if r > zero
                c=R(k,j)/r;
                s=R(k+1,j)/r;
                G=[c,-s; s,c];
                Q(k-j+1:n,k:k+1)=Q(k-j+1:n,k:k+1)*G;
                R(k:k+1,j:m)=G'*R(k:k+1,j:m);
                R(k+1,j)=0.0;
            end
        end
    end
