w3resource

Creating a 3x3 array and computing QR decomposition using NumPy

NumPy: Advanced Exercise-27 with Solution

Write a NumPy program to create a 3x3 array with random values and compute the QR decomposition.

QR decomposition is a factorization of a matrix into an orthogonal matrix 𝑄 and an upper triangular matrix 𝑅. In NumPy, the numpy.linalg.qr() function computes the QR decomposition of a given matrix. It's often used in numerical linear algebra for solving linear least squares problems, eigenvalue problems, and many other applications.

Sample Solution:

Python Code:

import numpy as np

# Create a 3x3 array with random values
array = np.random.random((3, 3))

# Compute the QR decomposition
q, r = np.linalg.qr(array)

# Print the original array, Q matrix, and R matrix
print("Original Array:\n", array)
print("Q Matrix:\n", q)
print("R Matrix:\n", r)

Output:

Original Array:
 [[0.86640332 0.76640485 0.65182287]
 [0.30254272 0.92296395 0.82323944]
 [0.31141372 0.21789583 0.88200149]]
Q Matrix:
 [[-0.89402381  0.26365732 -0.36222402]
 [-0.31218763 -0.9465117   0.08157502]
 [-0.32134143  0.18601187  0.92851455]]
R Matrix:
 [[-0.96910542 -1.04334106 -1.12317395]
 [ 0.         -0.63099672 -0.44328514]
 [ 0.          0.          0.65000109]]

Explanation:

  • Import NumPy: Import the NumPy library to work with arrays.
  • Create a Random 3x3 Array: Generate a 3x3 array filled with random values using np.random.random.
  • Compute QR Decomposition: Use np.linalg.qr to compute the QR decomposition of the array.
  • Print Results: Print the original array, the Q matrix, and the R matrix resulting from the QR decomposition.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Creating a 5x5 srray with random values and finding row minimum Indices using NumPy.
Next: Creating a 3x3 array and computing Cholesky Decomposition using NumPy.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.