3

I know that tensors have an apply method, but this only applies a function to each element. Is there an elegant way to do row-wise operations? For example, can I multiply each row by a different value?

Say

A =
  1 2 3
  4 5 6
  7 8 9

and

B =
  1
  2
  3

and I want to multiply each element in the ith row of A by the ith element of B to get

1 2 3
8 10 12
21 24 27

how would I do that?

Veech
  • 1,397
  • 2
  • 12
  • 20

2 Answers2

2

See this link: Torch - Apply function over dimension

(Thanks to Alexander Lutsenko for providing it. I just moved it to the answer.)

Community
  • 1
  • 1
Veech
  • 1,397
  • 2
  • 12
  • 20
1

One possibility is to expand B as follow:

 1  1  1
 2  2  2
 3  3  3
[torch.DoubleTensor of size 3x3]

Then you can use element-wise multiplication directly:

local A = torch.Tensor{{1,2,3},{4,5,6},{7,8,9}}
local B = torch.Tensor{1,2,3}
local C = A:cmul(B:view(3,1):expand(3,3))
deltheil
  • 15,496
  • 2
  • 44
  • 64
  • 2
    Thanks! Yeah, there are a few different ways to do it for my example, but I was wondering if there was a general way to apply a function to each row. I think Alexander's comment answers my first question. – Veech Dec 22 '15 at 14:38