How to multiple a matrix rows in R with a vector?

R ProgrammingServer Side ProgrammingProgramming

When we multiple a matrix with a vector in R, the multiplication is done by column but if we want to do it with rows then we can use transpose function. We can multiply the transpose of the matrix with the vector and then take the transpose of that multiplication this will result in the multiplication by rows.

Example

Consider the below matrix −

> M1<-matrix(1:25,nrow=5)
> M1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11   16    21
[2,] 2    7   12   17    22
[3,] 3    8   13   18    23
[4,] 4    9   14   19    24
[5,] 5   10   15   20    25
> V1<-1:5

Simple multiplication −

> M1*V1
   [,1] [,2] [,3] [,4] [,5]
[1,] 1    6   11   16   21
[2,] 4   14   24   34   44
[3,] 9   24   39   54   69
[4,] 16  36   56   76   96
[5,] 25  50   75  100  125

Row-wise Multiplication −

> t(t(M1)*V1)
   [,1] [,2] [,3] [,4] [,5]
[1,] 1   12   33   64  105
[2,] 2   14   36   68  110
[3,] 3   16   39   72  115
[4,] 4   18   42   76  120
[5,] 5   20   45   80  125

Let’s have a look at one more example −

> M2<-matrix(sample(1:100,25),nrow=5)
> M2
      [,1] [,2] [,3] [,4] [,5]
[1,]   72    5   36   11   76
[2,]   61   38   17   73   25
[3,]   96    9   62   79   64
[4,]   77   53   80   78   50
[5,]   81   15   21   43   23
> V2<-sample(1:100,5)
> V2
[1] 28 20 1 68 86
> t(t(M2)*V2)
[,1] [,2] [,3] [,4] [,5]
[1,] 2016 100 36 748 6536
[2,] 1708 760 17 4964 2150
[3,] 2688 180 62 5372 5504
[4,] 2156 1060 80 5304 4300
[5,] 2268 300 21 2924 1978
raja
Published on 12-Aug-2020 12:05:34
Advertisements