We can sort a matrix in Python using the numpy package. Here's how:
First, let's import numpy:
main.py19 chars2 lines
Next, let's create a matrix as a numpy array:
main.py53 chars2 lines
To sort the matrix in ascending order, we need to use the np.sort()
function:
main.py32 chars2 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.py64 chars2 lines
To sort the matrix in descending order, we can pass the axis
parameter to np.sort()
:
main.py82 chars2 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