sort a matrix in python

We can sort a matrix in Python using the numpy package. Here's how:

First, let's import numpy:

main.py
import numpy as np
19 chars
2 lines

Next, let's create a matrix as a numpy array:

main.py
matrix = np.array([[3, 2, 9], [1, 5, 8], [4, 7, 6]])
53 chars
2 lines

To sort the matrix in ascending order, we need to use the np.sort() function:

main.py
sorted_matrix = np.sort(matrix)
32 chars
2 lines

Note that this will sort each row of the matrix separately. If we want to sort the entire matrix, we can flatten it first:

main.py
sorted_matrix = np.sort(matrix.flatten()).reshape(matrix.shape)
64 chars
2 lines

To sort the matrix in descending order, we can pass the axis parameter to np.sort():

main.py
sorted_matrix_descending = np.sort(matrix, axis=None)[::-1].reshape(matrix.shape)
82 chars
2 lines

Here we used the [::1] to reverse the order of the flattened array before reshaping it back to the original shape of the matrix.

And that's it! We have now sorted a matrix in Python using numpy.

gistlibby LogSnag