How to create an orthogonal matrix using Python NumPy?
We can use the following Python code to create an orthogonal matrix using NumPy.
import numpy
n = 3
A = numpy.random.randint(low=1, high=10, size=(n, n))
Q, R = numpy.linalg.qr(A, mode="complete")
print("A: \n", A)
print("The Orthogonal Matrix Q: \n", Q)
I = numpy.matmul(Q, numpy.array(Q).transpose()).round()
print("QQ^T: \n", I)
Here, A is a square matrix of random integers. We are using the numpy.random.randint() function to create this matrix. The generated random integers are within the range [low, high). And the size argument specifies the size of the matrix. Here, size=(n, n) specifies that the created matrix has n rows and n columns.
A = numpy.random.randint(low=1, high=10, size=(n, n))
Now, we are using the numpy.linalg.qr() function to create an orthogonal matrix from A. The return value Q contains the orthogonal matrix.
Q, R = numpy.linalg.qr(A, mode="complete")
We can multiply this Q with its transpose to check whether Q is indeed orthogonal. As Q is an orthogonal matrix, we will get an identity matrix when we multiply Q with QT.
I = numpy.matmul(Q, numpy.array(Q).transpose()).round()
print("QQ^T: \n", I)
The output of the mentioned program will be:
A: [[2 8 8] [9 8 9] [4 1 7]] The Orthogonal Matrix Q: [[-0.19900744 0.91897461 0.34041403] [-0.89553347 -0.02945431 -0.44401829] [-0.39801488 -0.3932151 0.82883415]] QQ^T: [[1. 0. 0.] [0. 1. 0.] [0. 0. 1.]]








































0 Comments