3

I may be missing something obvious, but I can't find a way to compute this.

Given two tensors, I want to keep the minimum elements in each one of them as well as the sign.

I thought about

sign_x = torch.sign(x)
sign_y = torch.sign(y)
min = torch.min(torch.abs(x), torch.abs(y))

in order to eventually multiply the signs with the obtained minimums, but then I have no method to multiply the correct sign to each element that was kept and must choose one of the two tensors.

fjrivasf
  • 33
  • 4
  • Which sign do you want to end up with if `x` is negative and `y` is positive, but they have the same absolute value? – jdaz Jul 15 '20 at 04:56
  • Since they're floats I find that unlikely to happen, but a coin flip is probably the solution in that case. – fjrivasf Jul 15 '20 at 23:03

1 Answers1

2

Here is one way to do it. Multiply torch.sign(x) and torch.sign(y) by a tensor of booleans representing whether x or y is the result of the min calculation. Then take the logical or (|) of the two resulting tensors to combine them, and multiply that by the min calculation.

mins = torch.min(torch.abs(x), torch.abs(y))

xSigns = (mins == torch.abs(x)) * torch.sign(x)
ySigns = (mins == torch.abs(y)) * torch.sign(y)
finalSigns = xSigns.int() | ySigns.int()

result = mins * finalSigns

If x and y have the same absolute value for a certain element, in the code above the sign of x takes precedence. For y to take precedence, swap the order and use finalSigns = ySigns.int() | xSigns.int() instead.

jdaz
  • 5,964
  • 2
  • 22
  • 34