How to perform multiple boolean comparisons?

Hi,

I am very confused on how to perform multiple boolean comparisons, I normally use this in numpy to create a mask to select indices. These indices are then used to replace slices of a multidimensional array. So the numpy equivalent is:

a[ ( b > 5) | ( b < 20),: ] = 1 # where a and b are numpy arrays, respectively

Now in pytorch, indices must be LongTensor. So that type of comparison does not really work:

mask = ( b > 5 ).__or__.(b < 20) #this results in a ByteTensor

I can use this to select from the tensor but not assign. A long winded way of doing it:

mask = torch.LongTensor(np.argwhere((b > 5).numpy().astype(bool) | (b < 20).numpy().astype(bool)))
a[mask,:] =1

Is there an elegant way to do this?

Hi,

I think masked_fill_() is what you’re looking for :slight_smile:

Hi,

Thanks, I saw that. It works great for scalar fill. Is there a similar
approach for replacing the slice with a vector/matrix/tensor vector of the
same size?

P

masked_scatter_() ?

Hahaha, thanks that is perfect! This is a lesson in scrolling up in the documentation when you read it :smile: