Matrix multiplication in R

06 Jan

Matrix multiplication in R

If you have used R, you have probably had to deal with matrix multiplication I see a lot of times when programmers are frustrated when the martix multiplication does not work. Suppose you had the following lines of code:

x <- matrix(1:4, 2, 2)  # a sequence of numbers 1 to 4 in a 2x2 matrix

y <- matrix(rep(10, 4), 2,2) # 4 10s in a 2x2 matrix

 

Most people keep trying to literally multiply x and y as follows:

x*y, but this will only multiply the single items. For true matrix multiplication you have to use the following syntax:

 

x%*%y

 

The multiplication operand has to be within % sign for R to interpret it as a matrix multiplication.

copyright 2012 10jumps Llc.

copyright 2012 10jumps LLC.