function [R,c,s]=SparseQR(A,r,p)
% Perform QR factorization on sparse matrix A.
% A has nonzero entries below diagonal on {(r(i),p(i))}.
% (c(i),s(i)) is the cosine-sine pair to zero out (r(i),p(i)).
% R is the resulting upper triangular matrix.
% Assume no new nonzero results from rotations.

R=A;
for i=1:length(r)
[c(i),s(i)]=Rotate(R(p(i),p(i)),R(r(i),p(i)));
R([p(i),r(i)],p(i):end)=[c(i) s(i); -s(i) c(i)]*R([p(i),r(i)],p(i):end);
end