% Givens formula applied to the matrix from the textbook:

% Note this implementation is inefficient. 
% In practice we would not form Q or do multiplications explicity.

clc

% Set up the problem
t = (-1:.5:1)';
A = [1+0*t t t.^2];
b = [1 .5 0 .5 2]';
[m, n] = size(A);

Qt = eye(m);

while ( 1 ) % Loop forever
    A
    i = input('i? (Enter NaN to break) ');
    if ( isnan(i) ), break, end
    j = input('j? ');
    k = input('column? ');

    % Make g:
    a = A(:,k);
    ai = a(i);
    aj = a(j);
    c = ai/sqrt(ai^2+aj^2);
    s = aj/sqrt(ai^2+aj^2);
    G = eye(m);
    G(i,i) = c;
    G(j,j) = c;
    G(i,j) = s;
    G(j,i) = -s;

    % Update A, rhs b, and Q':
    A = G*A;
    b = G*b;
    Qt = G*Qt;
end

% At this stage, R should be upper-triangular
A
R = A(1:n,1:n)

% Solve the least squares problem:
x = R\b(1:n)

