QR
Overview
The QR
function computes the QR decomposition of a given matrix , such that , where is an orthogonal (or unitary) matrix and is an upper triangular matrix. This decomposition is fundamental in numerical linear algebra and is used in solving linear systems, least squares problems, and eigenvalue computations. The function uses the scipy.linalg.qr
implementation in ‘full’ mode, and allows the user to select whether to return the or matrix. Pivoting and check_finite options are not supported in this implementation. For more details, see the scipy.linalg.qr documentation .
This example function is provided as-is without any representation of accuracy.
Usage
To use the function in Excel:
=QR(matrix, return_type)
matrix
(2D list, required): The matrix to decompose, with shape (M, N).return_type
(str, required): Either “Q” to return the orthogonal matrix , or “R” to return the upper triangular matrix .
The function returns a 2D list representing either the or matrix, depending on the return_type
argument. If the input is invalid, an error message (string) is returned.
Examples
Example 1: Return Q for a 2x2 matrix
In Excel:
=QR({1,2;3,4}, "Q")
Expected output:
-0.316228 | -0.948683 |
-0.948683 | 0.316228 |
Example 2: Return R for a 2x2 matrix
In Excel:
=QR({1,2;3,4}, "R")
Expected output:
-3.162278 | -4.427189 |
0.0 | -0.632456 |
Example 3: Return Q for a 3x2 matrix
In Excel:
=QR({1,2;3,4;5,6}, "Q")
Expected output:
-0.169031 | 0.897085 | 0.408248 |
-0.507093 | 0.276026 | -0.816497 |
-0.845154 | -0.345033 | 0.408248 |
Example 4: Return R for a 3x2 matrix
In Excel:
=QR({1,2;3,4;5,6}, "R")
Expected output:
-5.91608 | -7.437357 |
0.0 | 0.828079 |
0.0 | 0.0 |
Python Code
import numpy as np
from scipy.linalg import qr as scipy_qr
def qr(matrix, return_type):
"""
Compute the QR decomposition of a matrix and return either Q or R.
Args:
matrix: 2D list representing the matrix to decompose.
return_type: 'Q' to return the orthogonal matrix Q, 'R' to return the upper triangular matrix R.
Returns:
2D list representing the requested matrix (Q or R), or an error message (str) if input is invalid.
This example function is provided as-is without any representation of accuracy.
"""
# Validate matrix
if not isinstance(matrix, list) or not matrix or not isinstance(matrix[0], list):
return "Invalid input: matrix must be a 2D list."
try:
a = np.array(matrix, dtype=float)
except Exception:
return "Invalid input: matrix must contain only numbers."
if a.ndim != 2:
return "Invalid input: matrix must be 2D."
if return_type not in ("Q", "R"):
return "Invalid input: return_type must be 'Q' or 'R'."
try:
q, r = scipy_qr(a, mode='full')
except Exception as e:
return f"scipy.linalg.qr error: {e}"
if return_type == "Q":
return q.tolist()
else:
return r.tolist()
Live Notebook
Edit this function in a live notebook .