Search code examples
luatorch

Subtract a vector across all columns in a tensor for Torch


Given a tensor of dimensions NxM and a vector Nx1, how do I subtract the vector in each column of the tensor in Torch?


Solution

  • One possibility is to use expand. Example:

    local A = torch.Tensor{{1, 2},{3, 4},{5,6}}
    local B = torch.ones(3)
    local C = A - B:view(3, 1):expandAs(A) -- make a 3x1 tensor before expand
    print(C)
    --  0  1
    --  2  3
    --  4  5
    -- [torch.DoubleTensor of size 3x2]