Sunday, November 17, 2024
Google search engine
HomeLanguagesCalculate the QR decomposition of a given matrix using NumPy

Calculate the QR decomposition of a given matrix using NumPy

In this article, we will discuss QR decomposition of a matrix. QR factorization of a matrix is the decomposition of a matrix say ‘A’ into ‘A=QR’ where Q is orthogonal and R is an upper-triangular matrix. We can calculate the QR decomposition of a given matrix with the help of numpy.linalg.qr(). 

Syntax : numpy.linalg.qr(a, mode=’reduced’)

Parameters :

  • a : matrix(M,N) which needs to be factored.
  • mode : it is optional. It can be :

Example 1:

Python3




import numpy as np
  
  
# Original matrix
matrix1 = np.array([[1, 2, 3], [3, 4, 5]])
print(matrix1)
  
# Decomposition of the said matrix
q, r = np.linalg.qr(matrix1)
print('\nQ:\n', q)
print('\nR:\n', r)


Output:

[[1 2 3]
 [3 4 5]]

Q:
 [[-0.31622777 -0.9486833 ]
 [-0.9486833   0.31622777]]

R:
 [[-3.16227766 -4.42718872 -5.69209979]
 [ 0.         -0.63245553 -1.26491106]]

Example 2:

Python3




import numpy as np
  
  
# Original matrix
matrix1 = np.array([[1, 0], [2, 4]])
print(matrix1)
  
# Decomposition of the said matrix
q, r = np.linalg.qr(matrix1)
print('\nQ:\n', q)
print('\nR:\n', r)


Output:

[[1 0]
 [2 4]]

Q:
 [[-0.4472136  -0.89442719]
 [-0.89442719  0.4472136 ]]

R:
 [[-2.23606798 -3.57770876]
 [ 0.          1.78885438]]

Example 3:

Python3




import numpy as np 
    
# Create a numpy array  
arr = np.array([[5, 11, -15], [12, 34, -51], 
                [-24, -43, 92]], dtype=np.int32) 
    
print(arr)
  
# Find the QR factor of array 
q, r = np.linalg.qr(arr) 
print('\nQ:\n', q)
print('\nR:\n', r)


Output:

[[  5  11 -15]
 [ 12  34 -51]
 [-24 -43  92]]

Q:
 [[-0.18318583 -0.08610905  0.97929984]
 [-0.43964598 -0.88381371 -0.15995231]
 [ 0.87929197 -0.45984624  0.12404465]]

R:
 [[-27.29468813 -54.77256208 106.06459346]
 [  0.         -11.22347731   4.06028083]
 [  0.           0.           4.88017756]]

RELATED ARTICLES

Most Popular

Recent Comments