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?

4

1 回答 1

19

在火炬

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

要选择一个范围,如前三个,请使用索引运算符

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

其中 1 是“开始”索引,3 是“结束”索引。

有关使用 Tensor.sub 和 Tensor.narrow 的更多替代方案,请参阅提取子张量


在 Lua 5.2 或更低版本中

Lua 表,例如您的dataset变量,没有选择子范围的方法。

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))

哪个打印

11    12   13

在 Lua 5.3 中

在 Lua 5.3 中,您可以使用table.move.

function subrange(t, first, last)
     return table.move(t, first, last, 1, {})
end
于 2015-07-08T23:20:33.693 回答