Python Program to find rank of a Matrix

Hi Coder! In this article, we are going to learn to find the rank of a Matrix using Python.

Before we write the code let us know more about Rank of a Matrix.

The rank of a Matrix

The rank of a Matrix refers to the maximum number of linearly independent columns or rows present in the Matrix.

We can say a row or a column is linearly independent if the row cannot be obtained by using the linear combinations of other rows.

Example:

2  3  4
4  6  8
6  9  12

In the above example, we can note that row2 can be obtained by multiplying row1 by 2 and row3 can be obtained by multiplying by 3. Therefore there is only one linearly independent row. So, we can say that the rank of the above matrix is 1.

Find rank of a Matrix in Python

To find the rank of a matrix in Python we are going to make use of method linalg.matrix_rank() which is defined inside NumPy Library. It returns the rank of a given matrix.

Let us first import numpy to get access to the method linalg.matrix_rank(). In this program I’m importing numpy as np.

`import numpy as np`

Now, we are going to declare a matrix using the array data structure in NumPy. numpy.array() represents a matrix by storing the numerical values of the lists.  Also, print the matrix row-wise to get a matrix format.

```my_matrix = np.array([[1, 2, 1], [3, 4, 7], [3, 6, 3]])
print("Matrix")
for row in my_matrix:
print(row)```

We can now calculate the rank of the matrix using np.linalg.matrix_rank(my_matrix).

Finally, print the value of the rank of the matrix.

```rank = np.linalg.matrix_rank(my_matrix)
print("Rank of the given Matrix is : ",rank)```

Output

```Matrix
[1 2 1]
[3 4 7]
[3 6 3]
Rank of the given Matrix is : 2```

Yahoo! In this article we have learned how to find the rank of a matrix in a simple way.