How to create a skew symmetric matrix using Python NumPy?
We can use the following Python code to create a skew symmetric matrix in NumPy.
import numpy n = 3 A = numpy.random.randint(low=1, high=10, size=(n, n)) B = numpy.triu(A, k=0) C = B.transpose() D = B - C print("A: \n", A) print("B: \n", B) print("Skew Symmetric Matrix D: \n", D)
Here, we are first creating a square matrix A with random integers. We are using the numpy.random.randint() function for that purpose. The generated random integers will be within the range [low, high). And the size argument specifies the size of the created matrix. size=(n, n) specifies that the created matrix will have n rows and n columns.
In our case, the program generates the following matrix as A:
A: [[9 9 4] [5 3 5] [6 8 9]]
Now, we are using the numpy.triu() function to create another matrix B such that the elements of B above its principal diagonal are the same as the elements of A above its principal diagonal. And as we are using k=0, the diagonal elements are also copied from A to B. And the rest of the elements of B are zeros. In other words, B is an upper triangular matrix created from A.
So, our program returns the following matrix as B:
B: [[9 9 4] [0 3 5] [0 0 9]]
Now, we are creating the matrix C which is the transpose of the upper triangular matrix B. So, C is a lower triangular matrix.
C = B.transpose() D = B โ C
So, our program returns the following matrix as C:
C: [[9 0 0] [9 3 0] [4 5 9]]
Please note that B is an upper triangular matrix. And C is a lower triangular matrix which is also the transpose of B. So, if we subtract C from B and create another matrix D, then the diagonal elements of D will be zeros. And the element in the ith row and jth column of D will be the negative of the element in the jth row and ith column of D. In other words, D will be a skew symmetric matrix.
So, our program returns the following matrix D as the output skew symmetric matrix:
A: [[9 9 4] [5 3 5] [6 8 9]] B: [[9 9 4] [0 3 5] [0 0 9]] C: [[9 0 0] [9 3 0] [4 5 9]] Skew Symmetric Matrix D: [[ 0 9 4] [-9 0 5] [-4 -5 0]]






0 Comments