Sam Comber
Sam Comber

Reputation: 1293

Change elements of boolean matrix to True based on value from another array

I'm trying to update the values of False elements in my boolean matrix to True based on the index value of that row which is contained in another numpy array.

Here is my array, change, that identifies the element that needs to be changed in the matrix, mask_matrix:

import numpy as np
mask_matrix = np.zeros((20, 25), dtype=bool)

change = np.array([ 6., 22., 22., 22., 22., 21., 22., 21., 17., 21., 22., 21., 22.,
       21., 22., 12.,  7.,  7., 12., 17.])

So every item in change tells which element to change in mask_matrix. E.g. change[0] = 6. should change the first row and 6th column to a 6 in the mask_matrix

I know I can change items like this,

mask[0,:][6] = True

But I need to find a more efficient way of doing this.

Does anybody have any advice as to how to do this? Preferably vectorised.

Upvotes: 4

Views: 925

Answers (1)

Crazy Coder
Crazy Coder

Reputation: 414

This should help:

mask_matrix[np.arange(change.size),change]=True

Which is basically using advanced indexing in numpy to call row-column elements of an array.

Upvotes: 3

Related Questions