我正在研究Torch/Lua并拥有dataset10个元素的数组.
dataset = {11,12,13,14,15,16,17,18,19,20}
Run Code Online (Sandbox Code Playgroud)
如果我写dataset[1],我可以读取数组的第一个元素的结构.
th> dataset[1]
11
Run Code Online (Sandbox Code Playgroud)
我需要在所有10个中只选择3个元素,但我不知道使用哪个命令.如果我在使用Matlab,我会写:dataset[1:3]但是这里不起作用.
你有什么建议吗?
rya*_*son 16
th> x = torch.Tensor{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Run Code Online (Sandbox Code Playgroud)
要选择范围(如前三个),请使用索引运算符:
th> x[{{1,3}}]
1
2
3
Run Code Online (Sandbox Code Playgroud)
其中1是'开始'指数,3是'结束'指数.
有关使用Tensor.sub和Tensor.narrow的更多替代方法,请参阅提取子张量
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))
Run Code Online (Sandbox Code Playgroud)
打印
11 12 13
Run Code Online (Sandbox Code Playgroud)
在Lua 5.3中你可以使用table.move.
function subrange(t, first, last)
return table.move(t, first, last, 1, {})
end
Run Code Online (Sandbox Code Playgroud)