R Tutorial R Charts & Graphs R Statistics R References

R - Matrix Multiplication operator



In R, the matrix multiplication operator %*% multiplies two matrices, if they are conformable. If one argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. If both are vectors of the same length, it will return the inner product (as a matrix).

Example:

Consider the example below, where two matrices are multiplied.

m1 <- matrix(c(1, 2, 3, 4), nrow=2)
m2 <- matrix(c(10, 20, 30, 40), nrow=2)

#multiplying m1 and m2
print(m1 %*% m2)

The output of the above code will be:

     [,1] [,2]
[1,]   70  150
[2,]  100  220

Example:

If one of the argument is a vector, it will be promoted to either a row or column matrix to make the two arguments conformable. Consider the example below:

v1 <- c(1, 2)
m1 <- matrix(c(10, 20, 30, 40), nrow=2)

#multiplying v1 and m1
print(v1 %*% m1)

The output of the above code will be:

     [,1] [,2]
[1,]   50  110

Example:

If both arguments are vectors of the same length, it returns the inner product of two vectors. Consider the example below:

v1 <- c(1, 2, 3, 4)
v2 <-c(10, 20, 30, 40)

#multiplying v1 and v2
print(v1 %*% v2)

The output of the above code will be:

     [,1]
[1,]  300

❮ R - Operators

5