4.3 Matrix Arithmetics
Just as with vectors, most arithmetric operations in R are applied to individual elements of a matrix. That applies to the standard arithmetric operations as well as to most functions.
> A <- matrix(c(0, -1, 1, 0), nrow=2)
> A
[,1] [,2]
[1,] 0 1
[2,] -1 0
> A*2
[,1] [,2]
[1,] 0 2
[2,] -2 0
> A/7
[,1] [,2]
[1,] 0.0000000 0.1428571
[2,] -0.1428571 0.0000000
> log(A)
Warning in log(A): NaNs produced
[,1] [,2]
[1,] -Inf 0
[2,] NaN -InfAlso just as with vectors, some functions are applied to the matrix as a whole.
However, R also supports the matrix product using the operator %*%.
> A <- matrix(1:4, nrow=2)
> A
[,1] [,2]
[1,] 1 3
[2,] 2 4
> B <- matrix(4:1, nrow=2);
> B
[,1] [,2]
[1,] 4 2
[2,] 3 1
> C <- A %*% B
> C
[,1] [,2]
[1,] 13 5
[2,] 20 8Of course, R will throw an error if the matrices are not conformable (i.e. if their dimensionality prohibits multiplication)
> matrix(1, nrow=3, ncol=3) %*% matrix(1, ncol=1, nrow=3)
[,1]
[1,] 3
[2,] 3
[3,] 3
> matrix(1, nrow=3, ncol=3) %*% matrix(1, ncol=2, nrow=1)
Error in matrix(1, nrow = 3, ncol = 3) %*% matrix(1, ncol = 2, nrow = 1): non-conformable argumentsR can also perform other standard matrix operations such as transposing or inverting a matrix. The transpose \(\boldsymbol{A}^T\) of a matrix \(\boldsymbol{A}\) (the swapping of rows and columns) is done using the function t().
> D <- matrix(1:9, nrow=3)
> D
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> t(D)
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9The inverse operation to a matrix multiplication. To invert a matrix, use the function solve(). Using the matrices \(\boldsymbol{A}\), \(\boldsymbol{B}\) and \(\boldsymbol{C}\) from above, we can show that \(\boldsymbol{C} \times \boldsymbol{B}^{-1} = \boldsymbol{A}\).
If you are unfamiliar with transposing, mulitplying or inverting matrices, don’t worry about it - but it does not hurt to know that they exists and R can perform them!
4.3.1 Exercises: Matrix Arithmetic
See Section 18.0.13 for solutions.
Consider a matrix \(\boldsymbol{Z}=\begin{pmatrix}-1&1\\1&-1\end{pmatrix}\), what is the matrix product \(\boldsymbol{Z}\times\boldsymbol{Z}^T\)?
What is the matrix product \(\begin{pmatrix}1&2\\3&4\end{pmatrix}\times \begin{pmatrix}-1&1&-1\\1&-1&1\end{pmatrix}\)?
What is the inverse of the matrix \(\begin{pmatrix}1&-3&7\\-2&0&1\\-1 & 1 & 0\end{pmatrix}\)?
Create two different 2 by 2 matrices named \(E\) and \(G\). \(E\) should contain the values 1 to 4 and \(G\) the values 5 to 8. Try out the following commands and by looking at the results see if you can figure out what is going on.
- \(\boldsymbol{E}*\boldsymbol{G}\) (multiplication *)
- \(\frac{E}{G}\)
- \(\boldsymbol{E}\times\boldsymbol{G}\) (matrix multiplication
%*%) - \(\boldsymbol{E}+\boldsymbol{G}\)
- \(\boldsymbol{E}-\boldsymbol{G}\)
- \(\boldsymbol{E}==\boldsymbol{G}\)