Skip to content

Multiply row of a matrix

3 messages · ac.dasilva at ulg.ac.be, William Dunlap, Jeff Newmiller

#
If we have the following matrix: 

Mat<-matrix(1:9, byrow=TRUE, nrow=3)
Mat

     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[3,]    7    8    9

 I would like to have each row multiplied by a different number. 
So I would like row 1 multiplied by 3, row2 by 1 and row3 by 0.5
Which would give: 

     [,1] [,2] [,3]
[1,]    3    6    9
[2,]    4    5    6
[3,]    3.5  4    4.5


Whatever I try, I always obtain 
     [,1] [,2] [,3]
[1,]    3    2  1.5
[2,]   12    5  3.0
[3,]   21    8  4.5

Which corresponds to the columns multiplied by the factors 

Could anyone help we to get the proper result ?
Best, Anne-Christine da Silva
#
[,1] [,2] [,3]
[1,]  3.0    6  9.0
[2,]  4.0    5  6.0
[3,]  3.5    4  4.5


Bill Dunlap
TIBCO Software
wdunlap tibco.com
On Tue, Feb 21, 2017 at 8:23 AM, <ac.dasilva at ulg.ac.be> wrote:
#
Why this works does not become clear until you actually pay attention to how matrices are laid out in memory as a vector, and how vector replication works.  Those ideas are not that difficult to learn, but they feel different than in other languages (e.g. matlab) and they make a huge difference when you want to speed things up. Read the appropriate section in the Introduction to R document that comes with R until you see what is happening, and ask for clarification if you are still lost.