0
0
R Programmingprogramming~5 mins

Matrix multiplication (%*%) in R Programming

Choose your learning style9 modes available
Introduction

Matrix multiplication helps combine two sets of numbers arranged in rows and columns to get a new set of numbers. It is useful for solving problems involving grids or tables of numbers.

When you want to combine two tables of numbers where the number of columns in the first matches the number of rows in the second.
When calculating transformations in graphics or geometry, like rotating or scaling shapes.
When working with data in statistics or machine learning that involves multiplying features by weights.
When solving systems of linear equations using matrices.
When combining multiple steps of calculations that can be represented as matrices.
Syntax
R Programming
result <- matrix1 %*% matrix2

The number of columns in matrix1 must be the same as the number of rows in matrix2.

The result will be a new matrix with rows from matrix1 and columns from matrix2.

Examples
Multiply two 2x2 matrices A and B to get matrix C.
R Programming
A <- matrix(c(1, 2, 3, 4), nrow=2, byrow=TRUE)
B <- matrix(c(5, 6, 7, 8), nrow=2, byrow=TRUE)
C <- A %*% B
Multiply a 2x3 matrix X by a 3x1 matrix Y to get a 2x1 matrix Z.
R Programming
X <- matrix(1:6, nrow=2)
Y <- matrix(7:9, nrow=3)
Z <- X %*% Y
Sample Program

This program creates two 2x2 matrices A and B, multiplies them using %*%, and prints the result matrix C.

R Programming
A <- matrix(c(1, 2, 3, 4), nrow=2, byrow=TRUE)
B <- matrix(c(5, 6, 7, 8), nrow=2, byrow=TRUE)
C <- A %*% B
print(C)
OutputSuccess
Important Notes

Matrix multiplication is not the same as element-wise multiplication (which uses * in R).

If the dimensions do not match, R will give an error.

Summary

Use %*% to multiply matrices when the inner dimensions match.

The result matrix has the outer dimensions of the two matrices.

This operation is common in math, data science, and graphics.