PyTorch – Element-wise signed min/max?

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.

Asked on July 16, 2020 in Python.
Add Comment
1 Answer(s)

Here is one way to do it. Multiply torch.sign(x) and torch.sign(y) by an array 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.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.