Search code examples
torch

why can not i use the transpose function without :?


i want to transpose a tensor in torch/lua.
actually i didn't fully get the idea of ":" but it really frustrates me i am a beginner to lua and torch. only this works :

x:t()

i want to do this

x = torch.t(x)

and when i do it i see error

attempt to call field 't' (a nil value)

i tried to search for a solution on the internet but i didn't find any.


Solution

  • In Lua, x:method(args) is syntactic sugar for x.method(x, args). It is a way to omit the self parameter.

    This being said, the easiest way to transpose a 2D tensor x is indeed x:t(). You can also write x.t(x) but it is more complicated.

    Finally torch does not have a method transpose or t as a field (unlike squeeze for example for which you can do both torch.squeeze(x) and x:squeeze()), I don't know the reason for this choice but it does not seem too painful to write x:t() and it is also the notation that is the closest to the mathematical notation, which I find convenient.