numpy, fill sparse matrix with rows from other matrix

Viewed 615

I have trouble figuring out what would be the most efficient way to do the following:

import numpy as np

M = 10
K = 10
ind = np.array([0,1,0,1,0,0,0,1,0,0])
full = np.random.rand(sum(ind),K)
output = np.zeros((M,K))
output[1,:] = full[0,:]
output[3,:] = full[1,:]
output[7,:] = full[2,:]

I want to build output, which is a sparse matrix, whose rows are given in a dense matrix (full) and the row indices are specified through a binary vector. Ideally, I want to avoid a for-loop. Is that possible? If not, I'm looking for the most efficient way to for-loop this.

I need to perform this operation quite a few times. ind and full will keep changing, hence I've just provided some exemplar values for illustration. I expect ind to be pretty sparse (at most 10% ones), and both M and K to be large numbers (10e2 - 10e3). Ultimately, I might need to perform this operation in pytorch, but some decent procedure for numpy, would already get me quite far.

Please also help me find a more appropriate title for the question, if you have one or more appropriate categories for this question.

Many thanks, Max

1 Answers
Related