Open In App

Numpy matrix.sort()

Last Updated : 19 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

numpy.matrix.sort() is a method in NumPy sort the elements of a matrix along a specified axis. It returns a sorted copy of the matrix without changing the original matrix.

Example:

Python
import numpy as np

m = np.matrix([[9, 2, 5], [6, 4, 1]])
sorted_m = m.sort(axis=1)
print(m)

Output
[[2 5 9]
 [1 4 6]]

Explanation: Each row is sorted independently.

Syntax

matrix.sort(axis=-1, kind='quicksort', order=None)

Parameters:

  • axis: Direction to sort; default is 1 (last axis), 0 for columns, 1 for rows.
  • kind: Sorting algorithm options include 'quicksort' (default), 'mergesort', 'heapsort', 'stable'.
  • order: For structured arrays, sort.

Returns: A new sorted matrix (not in-place).

Examples

Example 1: Sort a matrix column-wise

Python
import numpy as np

m = np.matrix([[3, 1], [2, 4]])
m.sort(axis=0)
print(m)

Output
[[2 1]
 [3 4]]

Explanation: Each column is sorted in ascending order.

Example 2: Using different sorting algorithms

Python
import numpy as np

m = np.matrix([[5, 3, 1], [4, 2, 6]])
m.sort(axis=1, kind='mergesort')
print(m)

Output
[[1 3 5]
 [2 4 6]]

Explanation: The matrix is sorted row-wise using mergesort.


Practice Tags :

Similar Reads