How to multiply corresponding row values in a matrix with single row matrix in R?

R ProgrammingServer Side ProgrammingProgramming

To multiply row values in a matrix having multiple rows with single row matrix in R, we can follow the below steps −

  • First of all, create a matrix with multiple rows and a matrix with single row.

  • Then, use mapply function to multiply row values in those matrices.

Example

Create the first matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(100,10),ncol=4)
M1

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

     [,1] [,2] [,3] [,4]
[1,]   6   6    6    10
[2,]  12   8    6    13
[3,]  14   9    6     5
[4,]  10   8   15     7
[5,]   6   4   10    11
[6,]   9  11   10    10
[7,]   5  11   10     8
[8,]  11  14    9    13
[9,]  12  6     6     7
[10,]  6 10    12    11
[11,]  7  9    12    10
[12,] 16 13    11    11
[13,] 12 11     7    14
[14,] 14 11     8     9
[15,] 11  9     7     8
[16,]  9 12    17     7
[17,] 14 13    14     8
[18,]  9 15    11     9
[19,]  6  9     7     9
[20,] 17  8    11     7
[21,] 14  8     9    14
[22,]  9 15    11    10
[23,]  6 12    10     7
[24,] 11  9    12    15
[25,] 16 11     5    11

Create the second matrix

Let’s create a matrix as shown below −

M2<-matrix(c(1,0,2,5),nrow=1)
M2

Output

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

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

Multiply values from two matrices

Using mapply function to multiply row values in the matrix M1 having multiple rows with single row matrix M2 −

M1<-matrix(rpois(100,10),ncol=4)
M2<-matrix(c(1,0,2,5),nrow=1)
mapply(`*`,M1,M2)

Output

 [1] 11  0 36 55  9  0 14 35 10  0 24 40 14  0 10 55 11  0 26 40  8  0 20 45 12
[26]  0 22 60  9  0 18 75 10  0 16 70  9  0 16 50 11  0 30 80 16  0  4 70 11  0
[51] 22 60 10  0  8 35 10  0 28 40  8  0 18 75  8  0 26 40  9  0 24 20 14  0 10
[76] 30  6  0 24 75  8  0 18 60 12  0 20 60  5  0 24 40 16  0 24 35 16  0 24 45
raja
Published on 10-Nov-2021 07:04:33
Advertisements