multiply matrices in r

In R, matrices can be multiplied using the %*% operator. The number of columns in the first matrix must be equal to the number of rows in the second matrix. Here's an example of how to multiply two matrices in R:

main.r
# create two matrices
A <- matrix(c(1, 2, 3, 4), nrow = 2)
B <- matrix(c(5, 6, 7, 8), nrow = 2)

# multiply matrices using %*%
C <- A %*% B
140 chars
7 lines

In this example, we create two 2x2 matrices, A and B. We then multiply them using the %*% operator and assign the result to a new matrix C. The resulting matrix C is also a 2x2 matrix, calculated as the product of the two input matrices.

Note that we could also use the array function to create matrices of higher dimensions and still use the %*% operator to multiply them.

gistlibby LogSnag