0

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.

Jrh
  • 37
  • 1
  • 9

1 Answers1

1

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.

DerWeh
  • 1,721
  • 1
  • 15
  • 26
  • Is there a reason to prefer `sorted.shape = matrix.shape` rather than using `ndarray.reshape`? – mgilson Nov 29 '16 at 22:13
  • I don't really know. The assignment seems for me pretty pythonic, as this is the way `setters` are implemented. But I honestly don't know, I think under the hood it will be pretty mush the same, just that `reshape` offers additional `order` settings. Probably `sorted.shape = ...`, `np.reshape(sroted, ...)` and `sorted.reshape(...)` all do the same, unless you use the `order` argument. – DerWeh Nov 29 '16 at 22:21
  • A short search gave me http://stackoverflow.com/questions/26856375/when-to-use-shape-and-when-to-use-reshape. So `reshape` might create a copy, whereas `shape = ` would result in an error if it is not possible to create a view. – DerWeh Nov 29 '16 at 22:21
  • Thanks, it works. The only thing you have a small bug in your code, it must be sorted[0,i], sorted[i,i] = sorted[i,i], sorted[0,i] – Jrh Nov 30 '16 at 13:01