3

In python, we use for i, _ in enumerate(wx): where wx is a row matrix or table. How can we use this in lua/torch. Any enumerate function?

Sibi
  • 2,221
  • 6
  • 24
  • 37

1 Answers1

1

In Lua, you have pairs and ipairs:

pairs (t)

If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.

Otherwise, returns three values: the next function, the table t, and nil, so that the construction

for k,v in pairs(t) do body end

will iterate over all key–value pairs of table t.

You can also use next, for creating your own custom enumeration:

next (table [, index])

Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.

The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numerical order, use a numerical for.)

The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • @Sibi It'd be `a= { 1, 2, 3 }` – hjpotter92 Jun 03 '16 at 07:14
  • In Lua if you use table then it works `a={1,2,3} for i,v in ipairs(a) do print(i,v) end` – moteus Jun 03 '16 at 07:15
  • Why isn't it working when I declare `a=torch.rand(4,5)`? I need it to work for these types of `a` – Sibi Jun 03 '16 at 07:20
  • `a` is not a table but a 2D tensor so use [`apply`](https://github.com/torch/torch7/blob/master/doc/tensor.md#applying-a-function-to-a-tensor) or convert it with `a:totable()`. See also: http://stackoverflow.com/questions/34123291/torch-apply-function-over-dimension – deltheil Jun 03 '16 at 07:56