JMuller
JMuller

Reputation: 55

Creating a matrix with at most one value in every row and column

From a matrix filled with values (see picture), I want to obtain a matrix with at most one value for every row and column. If there is more than one value, the maximum should be kept and the other set to 0. I know I can do that with np.max and np.argmax, but I'm wondering if there is some clever way to do it that I'm not aware of.

enter image description here

Here's the solution I have for now:

tmp = np.zeros_like(matrix)
for x in np.argmax(matrix, axis=0): # get max on x axis
    for y in np.argmax(matrix, axis=1): # get max on y axis
        tmp[x][y] = matrix[x][y]
matrix = tmp

Upvotes: 1

Views: 146

Answers (1)

Dominik Kern
Dominik Kern

Reputation: 128

The sparse structure may be used for efficiency, however right now I see a contradiction between at most one value for every row and column and your current implementation which may leave more than one value per row/column.

Either you need an order to prefer rows over columns or to go along an absolute sorting of all matrix values.

Just an idea which produces for sure at most one entry per row and column would be to, firstly select the maxima of rows, and secondly select from this intermediate matrix the maxima of columns:

import numpy as np
rows=5
cols=5
matrix=np.random.rand(rows, cols)

rowmax=np.argmax(matrix, 1)
rowmax_matrix=np.zeros((rows, cols))
for ri, rm in enumerate(rowmax):
    rowmax_matrix[ri,rm]=matrix[ri, rm]

colrowmax=np.argmax(rowmax_matrix, 0)
colrowmax_matrix=np.zeros((rows, cols))
for ci, cm in enumerate(colrowmax):
    colrowmax_matrix[cm, ci]=rowmax_matrix[cm, ci]

This is probably not the final answer, but may help to formulate the desired algorithm precisely.

Upvotes: 1

Related Questions