1

I am trying to implement an algorithm that iteratively removes some rows and columns of a matrix and continues processing the remaining submatrix. However, I would like to know the index of a value in the original matrix rather than the remaining submatrix.

For example, assume that a matrix x is built using

x = np.arange(9).reshape(3, 3)

Now, I would like to find the index of the element that is equal to 8 in the submatrix defined below:

np.where(x[1:, 1:] == 8)

By default, numpy returns (array[1], array[1]) because it is finding the element in the sliced submatrix. What I like to be returned instead is (array[2], array[2]), which is the index of 8 in the original matrix.

What is an efficient solution to this problem?

P.S.

  • The submatrix may be built arbitrarily. For example, I may need to keep rows, 0 and 1, but columns 0 and 2.
  • Each submatrix may be sliced in next iterations to make a smaller submatrix. I still would like to have access to the index in the original matrix. In other words, I am looking for a solution that works on submatrices of submatrices as well.
Matt
  • 796
  • 12
  • 25
  • How would you do this in-efficiently? One thought is to maintain some sort of row and column index arrays or mapping. Another idea is to work with masks rather than slicing or indexing. Instead of actually deleting elements, you mask them off. – hpaulj Apr 05 '18 at 02:14
  • Right, I found a solution similar to what you explained here and will post it as an answer. Thanks! – Matt Apr 05 '18 at 15:53

1 Answers1

0

I recently learned about indexing with arrays where submatrices of a matrix can be selected using another numpy array. I think what I can do to solve the problem is to map indices of the submatrix to elements of the indexing array.

For example, in the example above, the submatrix can be defined like this:

row_idx = np.array([1, 2])
col_idx = np.array([1, 2])

np.where(x[row_idx[:, None], col_idx] == 8)

This will still return the same (array[1], array[1]) output, but I can use these indices to lookup the elements of row_idx and col_idx in order to find the corresponding indices in the original matrix, i.e. row_idx[1] and col_idx[1].

Matt
  • 796
  • 12
  • 25