Python numpy linalg qr() function is used to calculate the QR factorization of a given matrix. In the term “qr”, q is orthonormal, and r is upper-triangular.
Numpy linalg qr()
The np qr() function computes the qr factorization of a matrix. Factor the matrix as qr, where q is orthonormal, and r is upper-triangular.
The linalg qr() function takes two main parameters :
Matrix: This is the matrix of size MxN whose qr factorization is to be found.
Mode: There is a total of 4 types of modes, which are:
If K = min(M, N), then
- ‘reduced’ : returns q, r with dimensions (M, K), (K, N) (default)
- ‘complete’: returns q, r with dimensions (M, M), (M, N)
- ‘r’: returns r only with dimensions (K, N)
- ‘raw’: returns h, tau with dimensions (N, M), (K,)
The options ‘reduced’, ‘complete, and ‘raw’ are new in numpy 1.8; see the notes for more information. The default is ‘reduced’, and to maintain backward compatibility with earlier versions of numpy, both it and the old default ‘full’ can be omitted.
Note that array h returned in ‘raw’ mode is transposed for calling Fortran.
The ‘economic’ mode is deprecated.
The modes ‘full’ and ‘economic’ may be passed using only the first letter for backward compatibility, but all others must be spelled out. See the Notes for more explanation.
The np qr() function returns a ndarray matrix or float or complex type.
This function also returns a matrix of type orthonormal when mode = “complete” the result is an orthogonal/unitary matrix depending on whether or not a is real/complex. The determinant may be either +/- 1 in that case.
Program to show the working of qr() when q is orthonormal.
# Program to show working of qr() when q is orthonormal import numpy as np # Declaring the first array arr1 = np.array([[0, 1], [1, 1], [1, 1], [2, 1]]) print("Original array is :\n", arr1) b = np.array([1, 0, 2, 1]) # Calculating qr (q, r) = np.linalg.qr(arr1) print("Value of q :", q) print("Value of r :", r) # Validating p = np.dot(q.T, b) print(np.dot(np.linalg.inv(r), p))
Original array is : [[0 1] [1 1] [1 1] [2 1]] Value of q : [[ 0. 0.8660254 ] [-0.40824829 0.28867513] [-0.40824829 0.28867513] [-0.81649658 -0.28867513]] Value of r : [[-2.44948974 -1.63299316] [ 0. 1.15470054]] [6.66133815e-16 1.00000000e+00]
In this example, we have declared a 2D array whose “qr” value is found, and we have validated it.
As per the rule, If A = qr such that q is orthonormal (which is always possible via Gram-Schmidt), then x = inv(r) * (q.T) * b.
We according to the rule, we have declared one array “b”, also, and for validating, we have followed the given equation.
That is it for the numpy linalg qr() function.