Suppose I have the following:
mat <- matrix(1:9, ncol = 3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
Now I would like to multiply each column of the matrix by a scalar
scalar = c(1,2,3)
I would like the first element of scalar to multiply the first column, the second element multiply the second column and the third scalar the third column.
To obtain the following output
[,1] [,2] [,3]
[1,] 1 8 21
[2,] 2 10 24
[3,] 3 12 27
Could anyone help me with this?
Another base R option using %*%
and diag
> mat %*% diag(scalar)
[,1] [,2] [,3]
[1,] 1 8 21
[2,] 2 10 24
[3,] 3 12 27