Vectors can be thought of as one-dimensional structures that can organize information, and matrices a two-dimensional extension.
Let’s do a little example. Suppose you want to make a multiplication table for your young cousin. Maybe she already knows her multiplication facts for numbers up through 5, and you want to make a table for some numbers larger than 5, let’s say 6 through 15, except leaving out 10, since 10 is too easy.
numbers <- c(6:9,11:15)
numbers
## [1] 6 7 8 9 11 12 13 14 15
length(numbers)
## [1] 9
So our multiplication table will end up being a 9-by-9 array of numbers.
Let’s make a 9-by-9 matrix mat
and fill it up with 0’s for now (we will overwrite those 0’s shortly).
mat <- matrix(data = 0, nrow = 9, ncol = 9)
mat
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
## [1,] 0 0 0 0 0 0 0 0 0
## [2,] 0 0 0 0 0 0 0 0 0
## [3,] 0 0 0 0 0 0 0 0 0
## [4,] 0 0 0 0 0 0 0 0 0
## [5,] 0 0 0 0 0 0 0 0 0
## [6,] 0 0 0 0 0 0 0 0 0
## [7,] 0 0 0 0 0 0 0 0 0
## [8,] 0 0 0 0 0 0 0 0 0
## [9,] 0 0 0 0 0 0 0 0 0
Here’s how we can fill in the table:
for(i in 1:9){
for(j in 1:9){
mat[i,j] <- numbers[i] * numbers[j]
}
}
mat
## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
## [1,] 36 42 48 54 66 72 78 84 90
## [2,] 42 49 56 63 77 84 91 98 105
## [3,] 48 56 64 72 88 96 104 112 120
## [4,] 54 63 72 81 99 108 117 126 135
## [5,] 66 77 88 99 121 132 143 154 165
## [6,] 72 84 96 108 132 144 156 168 180
## [7,] 78 91 104 117 143 156 169 182 195
## [8,] 84 98 112 126 154 168 182 196 210
## [9,] 90 105 120 135 165 180 195 210 225
Those are all of the products we wanted in our the multiplication table.
It’s not necessary, but it could be nice if the rows and columns were labelled with the numbers being multiplied. If we want, we can add row and column names to the matrix, like this:
rownames(mat) <- numbers
colnames(mat) <- numbers
mat
## 6 7 8 9 11 12 13 14 15
## 6 36 42 48 54 66 72 78 84 90
## 7 42 49 56 63 77 84 91 98 105
## 8 48 56 64 72 88 96 104 112 120
## 9 54 63 72 81 99 108 117 126 135
## 11 66 77 88 99 121 132 143 154 165
## 12 72 84 96 108 132 144 156 168 180
## 13 78 91 104 117 143 156 169 182 195
## 14 84 98 112 126 154 168 182 196 210
## 15 90 105 120 135 165 180 195 210 225
Here are a few examples of how we can extract parts of the matrix.
mat[1, 1]
## [1] 36
mat[9, 9]
## [1] 225
mat[9, 1:3]
## 6 7 8
## 90 105 120
mat[2:4, 1]
## 7 8 9
## 42 48 54
submat <- mat[numbers < 10, numbers > 10]
submat
## 11 12 13 14 15
## 6 66 72 78 84 90
## 7 77 84 91 98 105
## 8 88 96 104 112 120
## 9 99 108 117 126 135
submat[1:3, 5]
## 6 7 8
## 90 105 120
sum(submat[1:3, 5])
## [1] 315