MATLAB: Sparse and nonspare QR

linear algebraMATLABqrsparse matrices

I have question regarding the difference between the sparse and non-sparse QR as implimented R2012b. I have a matrix, X, that is mostly zeros which I wish to upper-triangularize. Because the matrix X is formed piecemeal from several sparse multiplications, the X is sparse. The results of:
a1 = qr(X)
and
a2 = triu(qr(full(X)))
are completely different. The few nonzero values end up in very different places. The code is for a square root DWY backward (Fisher type) filter as in Park and Kailath 96. Based on what I know of the problem and what the answer should be, a2 is correct (or at least I know a1 is incorrect because what should be the multiplication of 2 nonzero submatrices is zero in a1 but not a2).
Does anyone know why the two are different? Further is there a way to force qr(X) to produce the same result as triu(qr(full(X))) without resorting to the full() call?
Thank you

Best Answer

Sorry to take a while, busy week. Neither are wrong. You'll notice that the only difference in the outputs is that the sparse version puts all the rows with nonzero diagonals at the top of the matrix, while the full version leaves them in place. Thus, to get the nonzero pattern you want from the sparse matrix, do something like this
R = qr(A); % A is sparse
[I, J, S] = find(R); % Dismantle R
pivots = accumarray(I, J, [], @min); % Find min col in each nz row
I = pivots(I); % Translate the rows
R = sparse(I, J, S, size(Rs, 1), size(Rs, 2));
The matrices should be now be the same up the the signs of the rows. You can probably do this slightly more efficiently, but it should do the trick, avoiding full matrices.