---
title: linalg.qr
description: "计算矩阵的qr分解。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/240RC2/accel/kunpengaccel_kml_16_0552.html
sourcePath: /source/zh/kunpengboostkithistory/240RC2/accel/kunpengaccel_kml_16_0552.html
indexId: 1479ec8e6eb4834f718b4f6a3155bf7638f5c21b0d2276fa81a4e91e333e841d76
---
# linalg.qr

#### 功能描述

计算矩阵的qr分解。

将矩阵a因子分解为q和r矩阵，其中q是正交的，r是上三角形的。


#### 必选输入参数

| 参数名 | 类型 | 说明 |
| --- | --- | --- |
| a | array\_like, shape (…, M, N) | 维度至少为2的类数组对象。 |


#### 可选输入参数

| 参数名 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| mode | {‘reduced’,‘complete’,‘r’,‘raw’} | ‘reduce’ | 如果K=min（M,N），那么： “reduce”返回q，r，尺寸分别为(...,M,K)、(...,K,N)。 “complete”：返回q，r，尺寸分别为(...,M,M)、(...,M,N)。 “r”：仅返回尺寸为(...,K,N)的r。 “Raw”：返回h，tau尺寸分别为(...,N,M)、(...,K,)。 |


#### 返回数据

| 名称 | 类型 | 说明 |
| --- | --- | --- |
| q | ndarray of float or complex | 具有正交列的矩阵。当模式=“完成”时，结果是一个正交/酉矩阵，这取决于a是否为实/复数。在这种情况下，行列式可以是+/\- 1。如果输入数组中的维数大于2，则返回具有上述属性的一组矩阵。 |
| r | ndarray of float or complex | 如果输入数组中的维数大于2，上三角矩阵或一组上三角矩阵。 |
| (h, tau) | ndarrays of np.double or np.cdouble | 数组h包含与r一起生成q的豪斯霍尔德镜射算子。数组tau包含镜射算子的缩放因子。 |


#### 示例

```
>>> import numpy as np
>>> a = np.random.randn(9, 6)
>>> q, r = np.linalg.qr(a)
>>>
>>> np.allclose(a, np.dot(q,r))
True
>>>
>>> r2 = np.linalg.qr(a, mode='r')
>>> np.allclose(r, r2)
True
>>>
>>> a = np.random.normal(size=(3,2,2))
>>> q, r = np.linalg.qr(a)
>>> q.shape
(3, 2, 2)
>>> r.shape
(3, 2, 2)
>>> np.allclose(a, np.matmul(q,r))
True
>>>
>>> # Ax = b, 若A可分解为A = qr, 则 x = inv(r) * (q.T) * b
>>>
>>> A = np.array([[0,1], [1,1], [1,1], [2,1]])
>>> A
array([[0, 1],
[1, 1],
[1, 1],
[2, 1]])
>>> b = np.array([1, 0, 2, 1])
>>> q, r = np.linalg.qr(A)
>>> p = np.dot(q.T, b)
>>>
>>> np.dot(np.linalg.inv(r), p)
array([2.62287285e-16, 1.00000000e+00])
>>>
```
