1.2 Matrix multiplication, addition and transpose

You will need to be very solid in matrix multiplication for the course. If you haven’t done it in awhile, google `matrix multiplication youtube’ and you find lots of 5min videos to remind you.

In R, you use the %*% operation to do matrix multiplication. When you do matrix multiplication, the columns of the matrix on the left must equal the rows of the matrix on the right. The result is a matrix that has the number of rows of the matrix on the left and number of columns of the matrix on the right. \[(n \times m)(m \times p) = (n \times p)\]

A=matrix(1:6, 2, 3) #2 rows, 3 columns
B=matrix(1:6, 3, 2) #3 rows, 2 columns
A%*%B #this works
     [,1] [,2]
[1,]   22   49
[2,]   28   64
B%*%A #this works
     [,1] [,2] [,3]
[1,]    9   19   29
[2,]   12   26   40
[3,]   15   33   51
try(B%*%B) #this doesn't
Error in B %*% B : non-conformable arguments

To add two matrices use +. The matrices have to have the same dimensions.

A+A #works
     [,1] [,2] [,3]
[1,]    2    6   10
[2,]    4    8   12
A+t(B) #works
     [,1] [,2] [,3]
[1,]    2    5    8
[2,]    6    9   12
try(A+B) #does not work since A has 2 rows and B has 3
Error in A + B : non-conformable arrays

The transpose of a matrix is denoted \(\mathbf{A}^\top\) or \(\mathbf{A}^\prime\). To transpose a matrix in R, you use t().

A=matrix(1:6, 2, 3) #2 rows, 3 columns
t(A) #is the transpose of A
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
try(A%*%A) #this won't work
Error in A %*% A : non-conformable arguments
A%*%t(A) #this will
     [,1] [,2]
[1,]   35   44
[2,]   44   56