Sort matrix matrix based on its diagonal

I have a matrix that should have a diagonal, but the columns are mixed.

Messed up matrix

But I do not know how, without the obvious for the loop, to effectively exchange strings to get unity on the diagonals. I don’t even know which key I have to go through to sort.

Any suggestions?

+5
source share
2 answers

You can use numpy argmaxto determine the order of the columns of the target and change the order of your matrix using the argmax results as columns:

>>> z = numpy.array([[ 0.1 ,  0.1 ,  1.  ],
...                  [ 1.  ,  0.1 ,  0.09],
...                  [ 0.1 ,  1.  ,  0.2 ]])

numpy.argmax(z, axis=1)

>>> array([2, 0, 1]) #Goal column indices

z[:,numpy.argmax(z, axis=1)]

>>> array([[ 1.  ,  0.1 ,  0.1 ],
...        [ 0.09,  1.  ,  0.1 ],
...        [ 0.2 ,  0.1 ,  1.  ]])
+6
source
>>> import numpy as np
>>> a = np.array([[ 1. ,  0.5,  0.5,  0. ],
...               [ 0.5,  0.5,  1. ,  0. ],
...               [ 0. ,  1. ,  0. ,  0.5],
...               [ 0. ,  0.5,  0.5,  1. ]])
>>> np.array(sorted(a, cmp=lambda x, y: list(x).index(1) - list(y).index(1)))
array([[ 1. ,  0.5,  0.5,  0. ],
       [ 0. ,  1. ,  0. ,  0.5],
       [ 0.5,  0.5,  1. ,  0. ],
       [ 0. ,  0.5,  0.5,  1. ]])

It is actually sorted by rows, not columns (but the result is the same). It works by sorting by the index of the column it is in 1.

+3
source

All Articles