R Matrix Multiplication
Matrix multiplication pairs each row of one matrix with each column of another. The operator for it is %*%.
The elementwise trap
The star multiplies each cell by the cell in the same place. It never pairs a row with a column.
a <- matrix(c(1, 2, 3, 4), nrow = 2)
b <- matrix(c(5, 6, 7, 8), nrow = 2)
print(a * b)The true product
The same two matrices go through %*% here. Each result cell is a row of the first matrix paired with a column of the second.
a <- matrix(c(1, 2, 3, 4), nrow = 2)
b <- matrix(c(5, 6, 7, 8), nrow = 2)
print(a %*% b)Transpose a matrix
t() turns the rows of a matrix into columns. The value 3 moves from the first row to the second row.
a <- matrix(c(1, 2, 3, 4), nrow = 2)
print(a)
print(t(a))Shapes that cannot multiply
Both matrices have two rows and three columns. The left side has three columns but the right side has two rows, so the product stops.
x <- matrix(1:6, nrow = 2)
y <- matrix(1:6, nrow = 2)
print(x %*% y)Example
stock <- matrix(c(2, 1, 0, 3), nrow = 2)
print(stock)
print(t(stock))
print(stock %*% stock)Key points
- The * operator multiplies matching cells one pair at a time.
- %*% multiplies a row by a column and adds the products.
- The left matrix must have as many columns as the right matrix has rows.
- t() transposes a matrix and swaps its rows and columns.
- A product with mismatched shapes stops with a non-conformable error.
In this example, t() first shows the stock matrix flipped. The product then pairs the matrix with itself and the top left cell works out as 2 times 2 plus 0 times 1, which is 4.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does a %*% b compute?