  function P2Grade() 
% Checks out BasicLSrhs
% A small example to see if correct...
format short
m = 10;
n = 6;
A = randn(m,n);
b = A*[1 0 1 0 1 0]'+.01*randn(m,1);
[R_YOU,P_YOU,btilde_YOU] = BasicLSrhs(A,b);
[R_CVL,P_CVL,btilde_CVL] = BasicLSrhsCVL(A,b);
clc
R_YOU = R_YOU
R_CVL = R_CVL
The_Permutations     = [(1:n)*P_YOU;(1:n)*P_CVL]
The_btildes   = [btilde_YOU btilde_CVL]

% A larger example to see if the pivoting overhead is properly controlled... 
format short
m = 1000;
n = 600;
A = randn(m,n);
b = randn(m,1);
tic
[R_YOU,P_YOU,btilde_YOU] = BasicLSrhs(A,b);
t_YOU = toc;
tic
[R_CVL,P_CVL,btilde_CVL] = BasicLSrhsCVL(A,b);
t_CVL = toc;
fprintf('t_YOU/t_CVL = %6.3f\n',t_YOU/t_CVL)




  function [R1,P,btilde] = BasicLSrhsCVL(A,b)
% A is m-by-n with m>=n and b is m-by-1
% Computes an orthogonal Q and a permutation P so that Q'*A*P = R is
% upper triangular and P is a permutation determined by the 2-norm
% column pivoting strategy. btilde = Q'*b and R1 = R(1:n,1:n).
[m,n] = size(A);
% Initialize the vector of squared column sums and the vector
% of rhs inner products
c = zeros(1,n);
d = zeros(1,n);
for j=1:n
    c(j) = A(:,j)'*A(:,j);
    d(j) = A(:,j)'*b;
end
P = eye(n,n);
for j=1:n
    % Find the largest cosine. Note that the following is a multiple
    % of the "vector of remaining cosines"
    [tau,k] = max(abs(d(j:n)./sqrt(c(j:n))));
    k = k+j-1;
    % Swap columns k and j and update P, c, and d accordingly...
    A(:,[j k]) = A(:,[k j]);
    P(:,[j k]) = P(:,[k j]);
    c([j k]) = c([k j]);
    d([j k]) = d([k j]);
    % Compute the j-th Householder matrix I - beta*v*v' and update A and
    % b...
    [v,beta] = House(A(j:m,j));
    A(j:m,j:n) = A(j:m,j:n) - (beta*v)*(v'*A(j:m,j:n));
    b(j:m)     = b(j:m) - (beta*(v'*b(j:m)))*v;
    % Update column norms and inner products...
    c(j+1:n) = c(j+1:n) - A(j,j+1:n).^2;
    d(j+1:n) = d(j+1:n) - A(j,j+1:n)*b(j);
end
R1 = triu(A(1:n,1:n));
btilde = b;

% -1 if you forget to take abs of t he cosines
% -4 if you form things like eye(n,n) - beta*v*v'  This is a major
% mistake Read GVL4 5.1.4
