# Boolean expressions in Pytorch

Hi there,

I’ve just started to use use torch\ pytorch and so I’m just getting used to using tensors. I understand that for generating a boolean we can use the torch.geq(a,b), torch.leq(a,b) and so forth.
However, as I wanted to generate a new tensor, which looks at each element and if the condition is satisfied then the entry would be: 1, else : -1.

I originally used torch.geq(alpha, 0.5*torch.ones(alpha.size())), but I wasn’t sure how to effectively use this without using an if statement. So instead I just did the following on alpha:

# alpha - tensor of shape 2 x 2

``````alpha              = p_joint_new / p_joint_prev
a_values         = torch.tensor(alpha.size())
for i in range(alpha.size(0)):
for j in range(alpha.size(1)):
if alpha[i][j] > 0.5:
a_values[i][j] = 2*1 - 1
else:
a_values[i][j] = -1
``````

My way is slow, it is not elegant, nor error proof - is there a better way to do this in pytorch? As I will have to implement a number of conditions of this style.

Thank you for taking the time to reply and for the autograd library in pytorch!

You have to be a bit careful with the types (byte does not have negative numbers, so I added `.float()` below, `.long()` would also work if you wanted integers), but then the expression notation should work fine:

``````a = torch.rand(2,2)
print(2*(a>0.5).float()-1)
``````

Best regards

Thomas

1 Like

That is awesome!

Thank you for responding so quickly.

Regards,