# Why is Diagonal Sign Convention in QR Factorization Not Enforced?

**URL:** <https://discourse.julialang.org/t/why-is-diagonal-sign-convention-in-qr-factorization-not-enforced/122283>\
**Category:** General Usage\
**Created:** [November 5, 2024, 12:54pm UTC](https://discourse.julialang.org/t/why-is-diagonal-sign-convention-in-qr-factorization-not-enforced/122283 "2024-11-05T12:54:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mlouis9](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mlouis9/32/213224_2.png) [@mlouis9](https://discourse.julialang.org/u/mlouis9)\
**Post date:** [November 5, 2024, 12:54pm UTC](https://discourse.julialang.org/t/why-is-diagonal-sign-convention-in-qr-factorization-not-enforced/122283/1 "2024-11-05T12:54:03Z")

</div>

When performing the QR factorization of a m x n matrix A with full column rank (i.e. rank(A)=n), the (reduced or “skinny”) QR factorization is unique only if we enforce the sign of the diagonal entries of R. The convention is that these entries are chosen to be positive. Otherwise, there is ambiguity in the signs of the columns of Q and rows of R - see [this post](https://math.stackexchange.com/questions/641290/if-a-is-invertible-then-the-qr-factorization-is-unique-if-we-require-that-t). A simple test:

```julia
A = randn(5,2)
qr(A).R

```

gives a 2x2 R matrix with a negative diagonal entry (more often than not). Is there a reason why this uniqueness requirement isn’t enforced in `qr`? Isn’t this possibly problematic for algorithms (like the block Lanczos iteration) which rely on the sign convention of the QR factorization?

---

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [November 5, 2024, 1:05pm UTC](https://discourse.julialang.org/t/why-is-diagonal-sign-convention-in-qr-factorization-not-enforced/122283/2 "2024-11-05T13:05:59Z")

</div>

Any deterministic algorithm makes a unique choice for the QR factors. Different algorithms result in different choices.

The QR factorization in Julia uses the [Householder algorithm](https://github.com/mitmath/18335/blob/spring21/notes/lec6handout6pp.pdf) — this is not unique to Julia, it comes from LAPACK and is the most common algorithm for a variety of reasons. In this algorithm, the Q factors are not stored explicitly, but as a linear operator (a sequence of reflections), and it is not so natural or efficient to choose the signs of the R diagonals to be positive.

PS. In the rare cases where you need positive real diagonal elements of R, you can simply multiply Q by an additional diagonal scaling factor `Diagonal(sign.(diag(R))`. e.g. this is employed by [Mezzadri (2007)](https://arxiv.org/abs/math-ph/0609050) to generate uniformly distributed orthogonal matrices by QR-factorizing Gaussian random matrices.
