How to multiply single row matrix and a square matrix in R?


To multiply single row matrix and a square matrix in R, we can follow the below steps −

  • First of all, create the matrices.

  • Then, use %*% to multiply those matrices.

Example

Create the first matrix

Let’s create a matrix as shown below −

M1<-matrix(rpois(4,5),nrow=1)
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    4    5   7

Create the first matrix

Let’s create a matrix as shown below −

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

Output

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

Multiply the matrices

Using %*% to multiply the matrices M1 and M2 as shown below −

M1<-matrix(rpois(4,5),nrow=1)
M2<-matrix(rpois(100,5),ncol=4)
M1 %*% t(M2)

Output

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,] 107   66   88 148   63   112   96  95   95    86    110   97    66    88
    [,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25]
[1,] 97     116  103   126   86     86    89   169    81    112   77

Updated on: 15-Nov-2021

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements