Skip to content
Advertisement

A robust way to keep the n-largest elements in rows or colums in the matrix

I would like to make a sparse matrix from the dense one, such that in each row or column only n-largest elements are preserved. I do the following:

JavaScript

This approach works as intended but seems to be not the most efficient, and the robust one. What would you recommend to do it an better way?

The example of usage:

JavaScript

Advertisement

Answer

Instead of making another dense matrix, you can use coo_matrix to build up using only the values you need:

JavaScript

As for the rest, you can maybe short-circuit the second dimension, but your time savings will be completely dependent on your inputs

JavaScript

Testing:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement