在Tensor7中找到最小的正实数?

时间:2016-01-03 08:13:10

标签: lua torch

如果我有4D Tensor且Tensor包含实数

请告诉我如何在张量中找到大于零的最小正数

例如我有:

[ 0     -1     -3

6      5      0

0.3    0.6    0.9]

这里,大于零的最小正数是0.3。

3 个答案:

答案 0 :(得分:2)

一种可能性:

t = { 0,  -1,  -3,
      6,   5,   0,
      0.3, 0.6, 0.9 }

temp = {}
for _,n in ipairs(t) do
  if n > 0 then               --keep only positives
    temp[#temp+1] = n
  end
end
table.sort(temp)              --sorting them will bring the smallest first

print('Answer',temp[1])

更新:要找到最低值出现的位置,请将上述内容修改为:

t = { 0,  -1,  -3,
      6,   5,   0,
      0.3, 0.6, 0.9 }

temp = {}
for i,n in ipairs(t) do
  if n > 0 then               --keep only positives
    temp[#temp+1] = { n = n, p = i}
  end
end
table.sort(temp,function(a,b) return a.n < b.n end)      --sorting them will bring the smallest first

print('Answer '.. temp[1].n ..' at position '.. temp[1].p)

答案 1 :(得分:2)

另一种可能性:

t = { 0,  -1,  -3,
      6,   5,   0,
      0.3, 0.6, 0.9 }

for _,n in ipairs(t) do
  if n > 0 then               --only for positives
    if ans == nil then
      ans = n                 --first positive assumed lowest
    else
      if n < ans then ans = n end  --if a lower value is found, replaces previous one
    end
  end
end

print('Answer',ans)

更新:要找到最低值出现的位置,请将上述内容修改为:

t = { 0,  -1,  -3,
      6,   5,   0,
      0.3, 0.6, 0.9 }

for i,n in ipairs(t) do
  if n > 0 then               --only for positives
    if ans == nil then
      ans = n                 --first positive assumed lowest
      pos = i
    else
      if n < ans then         --if a lower value is found, replaces previous one
        ans = n
        pos = i               --keep position
      end
    end
  end
end

print('Answer '.. ans ..' at position '.. pos)

答案 2 :(得分:2)

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

0.3

如何获取所需元素的索引:

1)创建面具

mask = t:eq(minpos)

 0  0  0
 0  0  0
 1  0  0
[torch.ByteTensor of size 3x3]

2)以某种方式获取掩码的非零元素的索引。例如,使用此功能:

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]