Search code examples
arraysluatorch

Create a 2D list with variable length [torch]


I want to create a 2D list that can have elements of variable lengths inside, for example, if I have a 10x10 list in MATLAB, I can define it with:

z = cell(10,10)

and start assigning some elements by doing this:

z{2}{3} = ones(3,1)
z{1}{1} = zeros(100,1)
z{1}{2} = []
z{1}{3} = randn(20,1)
...

What is the optimal way to define such empty 2D list in torch? Moreover, is there a way to exploit the tensor structure to do this?

In python, I can do something along this to define an empty 10x10 2D list:

z = [[None for j in range(10)] for i in range(10)]

My best guess for torch is doing something like

z = torch.Tensor(10,10)

for i=1,10 do
  for j=1,10 do
    z[{{i},{j}}] = torch.Tensor()
  end
end

but, this does not work, and defining a tensor inside a tensor seems like a bad idea ...

This is a follow up to the question asked here (however in the link it is asked in python): Create 2D lists in python with variable length indexed vectors


Solution

  • Answer from Torch's Google Group forums. Agreeing that tables is the solution:

    z = {}
    
    for i=1,10 do
    
      z[i] = {}
      for j=1,10 do
        z[i][j] = torch.Tensor()
      end
    end