Search code examples
arraysluatorch

Torch / Lua, how to select a subset of an array or tensor?


I'm working on Torch/Lua and have an array dataset of 10 elements.

dataset = {11,12,13,14,15,16,17,18,19,20}

If I write dataset[1], I can read the structure of the 1st element of the array.

th> dataset[1]
11  

I need to select just 3 elements among all the 10, but I don't know which command to use. If I were working on Matlab, I would write: dataset[1:3], but here does not work.

Do you have any suggestions?


Solution

  • In Torch

    th> x = torch.Tensor{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    

    To select a range, like the first three, use the index operator:

    th> x[{{1,3}}]
    1
    2
    3
    

    Where 1 is the 'start' index, and 3 is the 'end' index.

    See Extracting Sub-tensors for more alternatives using Tensor.sub and Tensor.narrow


    In Lua 5.2 or less

    Lua tables, such as your dataset variable, do not have a method for selecting sub-ranges.

    function subrange(t, first, last)
      local sub = {}
      for i=first,last do
        sub[#sub + 1] = t[i]
      end
      return sub
    end
    
    dataset = {11,12,13,14,15,16,17,18,19,20}
    
    sub = subrange(dataset, 1, 3)
    print(unpack(sub))
    

    which prints

    11    12   13
    

    In Lua 5.3

    In Lua 5.3 you can use table.move.

    function subrange(t, first, last)
         return table.move(t, first, last, 1, {})
    end