# Matrix Selection and Indexing¶

Just like with vectors, we use the square bracket notation to select elements from a matrix. Since we have two dimensions to work with, we'll use a comma to separate our indexing for each dimension.

So the syntax is then:

example.matrix[rows,columns]

where the index notation (e.g. 1:5) is put in place of the rows or columns . If either rows or columns is left blank, then we are selecting all the rows and columns.

Let's work through some examples:

In [1]:

    mat <- matrix(1:50,byrow=TRUE,nrow=5)

In [2]:

    mat

Out[2]:

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30
31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50

In [3]:

    # Grab first row
    mat[1,]

Out[3]:

1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10

In [4]:

    #Grab first column
    mat[,1]

Out[4]:

1. 1
2. 11
3. 21
4. 31
5. 41

In [6]:

    # Grab first 3 rows
    mat[1:3,]

Out[6]:

1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30

In [8]:

    # Grab top left rectangle of:
    # 1,2,3
    # 11,12,13
    #
    mat[1:2,1:3]

Out[8]:

1 | 2 | 3
11 | 12 | 13

In [9]:

    # Grab last two columns
    mat[,9:10]

Out[9]:

9 | 10
19 | 20
29 | 30
39 | 40
49 | 50

In [14]:

    # Grab a center square of:
    # 15,16
    # 25,26
    mat[2:3,5:6]

Out[14]:

15 | 16
25 | 26

Great job! You should practice this! Just pick out blocks from the matrix and see if you can successfully index them. Up next we will learn about Matrix Arithmetic!