0

Suppose I have a scaling factor such like:

sf<-c(0.9, 0.8, 1.1)

and a matrix:

m0<-matrix(c(1:6), nrow=2, ncol=3)     
      [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

What's the best way to multiply each column of m with the corresponding element of sf such like

m1<-matrix(c(0.9, 1.8, 2.4, 3.2, 5.5, 6.6), 2, 3)
     [,1] [,2] [,3]
[1,]  0.9  2.4  5.5
[2,]  1.8  3.2  6.6
David Z
  • 6,641
  • 11
  • 50
  • 101
  • Seems like a dupe to me, but I could be convinced otherwise. – Frank Nov 11 '15 at 21:33
  • These are different questions! can you take a look in details? – David Z Nov 11 '15 at 21:35
  • I'm looking at the details. Could you be more specific? The other question starts "I have a matrix mat and a vector v. I would like to multiply first column of matrix matby first element of vector v and multiply the second column of matrix mat by second element of vector v" which sounds the same as your "multiply each column of m with the corresponding element of sf" to me. – Frank Nov 11 '15 at 21:38

2 Answers2

2

Probably not the "best way", but you could use sweep().

sweep(m0, 2, sf, "*")
#      [,1] [,2] [,3]
# [1,]  0.9  2.4  5.5
# [2,]  1.8  3.2  6.6
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
2

Or you could use col

m0 * sf[col(m0)]
#      [,1] [,2] [,3]
# [1,]  0.9  2.4  5.5
# [2,]  1.8  3.2  6.6

Or a double transpose

t(t(m0) * sf)
#      [,1] [,2] [,3]
# [1,]  0.9  2.4  5.5
# [2,]  1.8  3.2  6.6
David Arenburg
  • 91,361
  • 17
  • 137
  • 196