使用NumPy计算一个给定矩阵的QR分解
在这篇文章中,我们将讨论矩阵的QR分解。矩阵的QR分解是将矩阵(如A)分解为 “A=QR”,其中Q是正交的,R是一个上三角矩阵。我们可以在numpy.linalg.qr()的帮助下,计算一个给定矩阵的QR分解。
语法 : numpy.linalg.qr(a, mode='reduced')
参数 :
- a : 矩阵(M,N),需要被分解。
- mode : 它是可选的。它可以是。
示例 1:
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)
输出:
[[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]]
示例 2:
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)
输出:
[[1 0]
[2 4]]
Q:
[[-0.4472136 -0.89442719]
[-0.89442719 0.4472136 ]]
R:
[[-2.23606798 -3.57770876]
[ 0. 1.78885438]]
示例 3:
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)
输出:
[[ 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]]