How to multiply corresponding values from two matrices in R?

R ProgrammingServer Side ProgrammingProgramming

To multiply corresponding values from two matrices in R, we can follow the below steps −

  • First of all, create two matrices.

  • Then, use mapply function to multiply corresponding values from those two matrices.

Example

Create the first matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(100,5),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,]   2    6    8    3
[2,]  10    4    7    5
[3,]   5    5    5    8
[4,]   8    8    3    3
[5,]   9    5    8    3
[6,]   7    5    3    9
[7,]  12    9    3    5
[8,]   6    4    6    5
[9,]   5    6    4    4
[10,]  7    5    3    9
[11,]  6    6    4    6
[12,]  2    7    3    6
[13,]  7    8    7    5
[14,]  5    6    8    6
[15,]  4    4    7    4
[16,]  4    8    8    1
[17,]  4    3    3    6
[18,]  5    4    7    3
[19,]  7    7    7    8
[20,]  5    4    4    3
[21,]  4    5    3    5
[22,]  5    4    9    5
[23,]  5    6    5    3
[24,]  4    2    6    5
[25,]  5    3    5    3

Create the second matrix

Let’s create a matrix as shown below −

M2<-matrix(rpois(100,2),ncol=4)
M2

Output

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

Multiply corresponding values from two matrices

Using mapply function to multiply corresponding values in matrices M1 and M2 −

M1<-matrix(rpois(100,5),ncol=4)
M2<-matrix(rpois(100,2),ncol=4)
mapply(`*`,M1,M2)

Output

 [1]  8 20 10  0 27 28 48  6 15 14  0  0 14 10  4  0  0 20 35 10  4 20 10 16  5
[26] 12  8 15 24  5 10 18  0  0 15 12  0 16  0  8 40  6  4 21  0 10  4 12  6  6
[51] 16 21  5  3  8  0 15 24 16  0  0  6 28 32 14 24  3 14 14 12  9 27  5 12 10
[76]  9 40  8  6  9 27 20  5 12  0  6 24  5  0 12  5 12  6 16  6 10 30  6 20 15
raja
Published on 09-Nov-2021 06:19:48
Advertisements