python-scipyHow do I use Python Scipy to calculate a QR decomposition?
The QR decomposition is the factorization of a matrix into an orthogonal matrix and an upper triangular matrix. To calculate a QR decomposition in Python Scipy, the scipy.linalg.qr
function can be used.
import scipy
import numpy as np
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
Q, R = scipy.linalg.qr(A)
print(Q)
print(R)
Output example
[[-0.12309149 0.90453403 0.40824829]
[-0.49236596 0.30151134 -0.81649658]
[-0.86164044 -0.30151134 0.40824829]]
[[-8.12403840e+00 -9.60113630e+00 -1.10782342e+01]
[ 0.00000000e+00 9.04534034e-01 1.80906807e+00]
[ 0.00000000e+00 0.00000000e+00 -1.11164740e-15]]
The scipy.linalg.qr
function takes the matrix A
as an argument and returns two matrices, Q
and R
. Q
is an orthogonal matrix, and R
is an upper triangular matrix. In the example code, the matrix A
is a 3x3 matrix, and the output is two 3x3 matrices.
Parts of the code:
import scipy
: imports the scipy libraryimport numpy as np
: imports the numpy library with the aliasnp
A = np.array([[1,2,3],[4,5,6],[7,8,9]])
: creates a 3x3 matrixA
Q, R = scipy.linalg.qr(A)
: calculates the QR decomposition ofA
and assigns the orthogonal matrixQ
to the variableQ
and the upper triangular matrixR
to the variableR
print(Q)
: prints the matrixQ
print(R)
: prints the matrixR
Helpful links
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use the trapz function in Python SciPy?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to read and write WAV files?
- How do I convert a Python numpy array to a list?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How can I use Python and SciPy to implement a quantum Monte Carlo simulation?
See more codes...