11

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?

2 Answers 2

19

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
2
  • Thanks @rpattiso. But how to do it with a simple table? Jul 9, 2015 at 17:29
  • @DavideChicco.it see update for one that creates a new table. Lua's iterators or metatables can be used if you want to avoid copying the values. If you're using torch, tensors are more convenient and efficient. Jul 9, 2015 at 17:44
0

What about

dataset = {11,12,13,14,15,16,17,18,19,20}
subdata = { unpack( dataset, 1, 3 ) }

it makes a copy of the values of dataset from 1 to 3, so the original dataset can not be modified through subdata. In this aspect, this is different in that way from the tensor solution. Maybe in your case the copy is enough.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.