2

I would like to do the below but using PyTorch.

The below example and description is from this post.

I have a numeric matrix with 25 columns and 23 rows, and a vector of length 25. How can I multiply each row of the matrix by the vector without using a for loop?

The result should be a 25x23 matrix (the same size as the input), but each row has been multiplied by the vector.

Example Code in R (source: reproducible example from @hatmatrix's answer):

matrix <- matrix(rep(1:3,each=5),nrow=3,ncol=5,byrow=TRUE)

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    1    1    1
[2,]    2    2    2    2    2
[3,]    3    3    3    3    3

vector <- 1:5

Desired output:

     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    2    4    6    8   10
[3,]    3    6    9   12   15

What is the best way of doing this using Pytorch?

avgJoe
  • 832
  • 7
  • 24

1 Answers1

4

The answer was so trivial that I overlooked it.

For simplicity I used a smaller vector and matrix in this answer.

Multiply rows of matrix by vector:

X = torch.tensor([[1,2,3],[5,6,7]])                                                                                                                                                                          
y = torch.tensor([7,4])                                                                                                                                                                                   
X.transpose(0,1)*y
# or alternatively
y*X.transpose(0,1)

output:

tensor([[ 7, 20],
        [14, 24],
        [21, 28]])

tensor([[ 7, 20],
        [14, 24],
        [21, 28]])

Multiply columns of matrix by vector:

To multiply the columns of matrix by a vector you can use the same operator '*' but without the need to transpose the matrix (or vector) first

X = torch.tensor([[3, 5],[5, 5],[1, 0]])                                                                                                                                                                          
y = torch.tensor([7,4])                                                                                                                                                                                   
X*y
# or alternatively
y*X

output:

tensor([[21, 20],
        [35, 20],
        [ 7,  0]])

tensor([[21, 20],
        [35, 20],
        [ 7,  0]])
avgJoe
  • 832
  • 7
  • 24