Section 18 Matrix Multiplication
Download this Rmd file from GitHub
Here we will practice multiplying matrices in R. First, let’s define a few matrices.I’m using a trick here. By putting the assignment in parentheses, it assigns the matrix and displays it.s
## [,1] [,2] [,3]
## [1,] 1 4 1
## [2,] 2 5 1
## [3,] 3 6 -1
## [,1] [,2] [,3]
## [1,] 1 1 0
## [2,] -1 1 2
## [3,] 1 1 1
## [,1] [,2] [,3] [,4]
## [1,] 2 1 1 3
## [2,] 1 0 -3 2
## [3,] 1 1 1 1
We multiply using the %*%
command. As seen here:
## [,1] [,2] [,3]
## [1,] -2 6 9
## [2,] -2 8 11
## [3,] -4 8 11
Note that
## [,1] [,2] [,3]
## [1,] 3 9 2
## [2,] 7 13 -2
## [3,] 6 15 1
What do these last two multiplications say about the matrix product AB and BA? This is a very important property (or, perhaps, lack of property) of matrix multiplication.
Try multiplying BC and CB. What happens? And why?
The transpose of a matrix is computed by
t(A)
. Compute the transpose of the matrices A, B, C and be sure that you all understand what it does.The command
diag(n)
gives the n x n identity matrix. This is denoted \(I_n\). For example, here is \(I_3\).
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
Compute \(I_2\), \(I_4\), and \(I_5\) and be sure you all agree on what the identity matrix is.
Multiply the matrices A and B by the appropriately-sized identity matrix. Multiply both ways, A I and I A, and agree upon what multiplying by the identity does.
Multiply C by an identity matrix I C and C I. You might need a different size on the left and on the right.
Our topic for Thursday (tomorrow) is the inverse of a matrix. You compute the inverse of the matrix A with
solve(A)
. Try this
## [,1] [,2] [,3]
## [1,] -0.5 -0.5 1
## [2,] 1.5 0.5 -1
## [3,] -1.0 0.0 1
## [,1] [,2] [,3]
## [1,] 1 0 0
## [2,] 0 1 0
## [3,] 0 0 1
- Multiply A by its inverse and look closely at the answer you get.
## [,1] [,2] [,3]
## [1,] -1.8333333 1.6666667 -0.1666667
## [2,] 0.8333333 -0.6666667 0.1666667
## [3,] -0.5000000 1.0000000 -0.5000000
## [,1] [,2] [,3]
## [1,] 1.000000e+00 0.000000e+00 0.000000e+00
## [2,] 3.330669e-16 1.000000e+00 -1.110223e-16
## [3,] 1.110223e-16 -2.220446e-16 1.000000e+00
- Some matrices do not have inverses. Try computing the inverse of the following matrices. We will discuss this tomorrow!
## [,1] [,2]
## [1,] 3 -2
## [2,] 5 1
## [,1] [,2]
## [1,] 4 5
## [2,] 3 4
## [,1] [,2]
## [1,] 4 10
## [2,] 2 5
- Enter the matrix A in problem 3.7 in the homework. Then compute the matrix G which is A times its transpose. Discuss its meaning.