2

I am trying to perform logical element-wise opertaions on tensors, but it seems "and" keyword performs logical or, while "or" keyword performs logical and :

    a = torch.zeros(3)
    a[1] = 1                      -- a will be [1,0,0]
    b = torch.ones(3)
    b[3] = 0                      -- b will be [1,1,0]
    c = torch.eq(a,1) and torch.eq(b,1) 
    d = torch.eq(a,1) or  torch.eq(b,1)

I was expecting c to become [1,0,0] since it would make sense to have 1 only in positions where both a and b are equal to 1. Also I was expecting d to become [1,1,0] since those are the positions where either a or b are equal to 1. To my surprise, the results are completely the opposite! Any explanations?

Autonomous
  • 8,935
  • 1
  • 38
  • 77
kerrigan
  • 87
  • 2
  • 9
  • Warning: according to the answer, this method is absolutely incorrect for element-wise logical operations on Tensors. – kerrigan Mar 17 '17 at 15:23

1 Answers1

1

According to Lua docs:

The operator and returns its first argument if it is false; otherwise, it returns its second argument. The operator or returns its first argument if it is not false; otherwise, it returns its second argument

In this case, that behaviour is happening just as a "coincidence". It will return the second argument (Tensor a) while applying the and operator and the first argument (Tensor b) while applying the or operator. Also, tensor a corresponds to the element-wise logical and while tensor b corresponds to the element-wise logical or.

Manuel Lagunas
  • 2,611
  • 19
  • 31
  • You are right! I just figured using torch.cmax(a, b) would be equivalent to "a or b" and torch.cmin(a, b) to "a and b" (you need to make sure a and b are logical tensors; i.e. they only contain 1s and 0s) – kerrigan Mar 17 '17 at 15:38