# What is the numpy.linalg.qr() Method in Python

Numpy.linalg.qr() is “used to calculate the qr factorization of a matrix.” Factor the matrix an as qr, where q is orthonormal, and r is upper-triangular.

## Syntax

numpy.linalg.qr(matrix, mode)

## Parameters

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:

1. reduced
2. complete
3. r
4. raw

If K = min(M, N), then

1. ‘reduced’: returns q, r with dimensions (M, K), (K, N) (default)
2. ‘complete’: returns q, r with dimensions (M, M), (M, N)
3. ‘r’: returns r only with dimensions (K, N)
4. ‘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.

## Return Value

The np.qr() method returns a ndarray matrix, float, or complex type.

## Example 1: How to Use np.linalg.qr() Method

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))

Output

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]

## Example 2: QR factorization of 2X4 matrix

import numpy as np

# 2x4 matrix
A = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

# QR factorization
Q, R = np.linalg.qr(A)

print("Q = \n", Q)
print("R = \n", R)

Output

Q =
[[-0.19611614 -0.98058068]
[-0.98058068 0.19611614]]

R =
[[-5.09901951 -6.27571632 -7.45241314 -8.62910995]
[ 0. -0.78446454 -1.56892908 -2.35339362]]

## Example 3: QR factorization of 3X3 matrix

Output

Q =
[[-0.12309149 0.90453403 0.40824829]
[-0.49236596 0.30151134 -0.81649658]
[-0.86164044 -0.30151134 0.40824829]]
R =
[[-8.12403840e+00 -9.60113630e+00 -1.10782342e+01]
[ 0.00000000e+00 9.04534034e-01 1.80906807e+00]
[ 0.00000000e+00 0.00000000e+00 -7.58790979e-16]]

That’s it.

This site uses Akismet to reduce spam. Learn how your comment data is processed.