Search code examples
luatorch

Find a smallest positive real number in an Tensor7?


If I have 4D Tensor and the Tensor contains real numbers

Could you please tell how to find the smallest positive number greater than zero in the tensor

for example I have:

[ 0     -1     -3

6      5      0

0.3    0.6    0.9]

Here the smallest positive number greater than zero is 0.3.


Solution

  • t = torch.Tensor({{0, -1, -3}, {6, 5, 0}, {0.3, 0.6, 0.9}})
    minpos = torch.min(t[t:gt(0)])
    
    0.3
    

    How to get index(es) of desired element(s):

    1) Create the mask

    mask = t:eq(minpos)
    
     0  0  0
     0  0  0
     1  0  0
    [torch.ByteTensor of size 3x3]
    

    2) Somehow get the indexes of non-zero elements of the mask. For example, using this function:

    function indexesOf(mask)
        local lin_indices = torch.linspace(1, mask:nElement(), mask:nElement())[mask]
        if lin_indices:nElement() == 0 then return nil end
    
        local sp_indices = torch.LongTensor(mask:nDimension(), lin_indices:nElement())
        sp_indices[1] = lin_indices - 1
        local divisor = mask:nElement()
        for d = 1, mask:nDimension() - 1 do
            divisor = divisor / mask:size(d)
            local fdiv = torch.div(sp_indices[d], divisor)
            sp_indices[d + 1] = sp_indices[d] - fdiv * divisor
            sp_indices[d] = fdiv
        end
        return sp_indices:t() + 1
    end
    
    indexes = indexesOf(mask)
    
     3  1
    [torch.LongTensor of size 1x2]