Vadim Vadim - 1 year ago 54
Python Question

Sort the numpy matrix by the minimum values and display minimum values on the diagonal of matrix

No matter how the other elements are positioned, is important only the values along the diagonal.

For example I have matrix:

matrix = [[1, 3, 2],
[2, 5, -9],
[3, 4, 6]]

What I want to achieve is something the same as:

[[-9, 3, 2],
[6, 1, 5],
[3, 4, 2]]

I have tried:

>>> np_matrix = np.array(matrix)
>>> np_matrix.diagonal()
array([1, 5, 6])

>>> np.sort(np_matrix)
array([[ 1, 2, 3],
[-9, 2, 5],
[ 3, 4, 6]])

I think that I can get something from these methods, but I can not figure out how to make them work together. I appreciate all the help I can get.

Answer Source

I am not really sure what you want. But maybe something like

sorted = np.sort(matrix, axis=None) #sorts flattened matrix

Now you have reshape it, and then change the diagonal elements with the first row:

sorted.shape = matrix.shape
for i in xrange(1, matrix.shape[0]):  # first element already in order
     sorted[0, i], sorted[i, i] = sorted[i, i], sorted[0, i]

But honestly I would first question if that really is what you want. It doesn't seem really useful to me. Isn't it maybe enough to get an array with the smallest elements

diag_lowest = np.sort(matrix, axis=None)[:matrix.shape[0]]

and keep the matrix as it is.