This section will discuss Python matrix indexing.

In order to select specific items, Python matrix indexing must be used. Lets start with the basics, just like in a list, indexing is done with the square brackets `[]`

with the index reference numbers inputted inside.

However, we have to remember that since a matrix is two dimensional (a mix of rows and columns), our indexing code should also should have two inputs.

So for Python matrix indexing the notation is `[row index, column index].`

Also remember that in Python indexing starts at 0.

Let’s use an example for a better understanding.

Input:

matrix= np.array([[1,2,3],[4,5,6],[7,8,9]]) print(matrix)

Output:

[[1,2,3] [4,5,6] [7,8,9]]

**a. Selecting entire rows**

As we have discussed before the first element in the bracket is the row. If we leave the second item blank an entire row will be selected `[row index, ]`

. Let’s select the second row.

Input:

print (matrix[1,])

Output

[4,5,6]

Imputing `matrix[1, : ]`

will output the same result.

The `:`

denotes the range of selection, this will be discussed later.

**b. Selecting entire columns**

We can select entire columns in a matrix. The second element of the bracket is for column selection. Only fill up the second element in the bracket `[ : , column index]`

. For entire column selection, `:`

is required to be inputted inside the bracket. An error will result if the `:`

is not inputted.

Let’s select the last column.

Input:

matrix[ : , 2]

Output:

array([3,6,9])

**c. Selecting single items in the matrix **

Now that you have learned how to select entire rows and columns. We can now select single items of the matrix by combining the indexation techniques. To select specific items in the matrix fill up both the first and second elements of the bracket.

For example let’s select the value 7.

Input:

matrix[2,0]

Output:

7

**d. Selecting a range in the matrix (sub-matrix)**

As discussed the `:`

is used to select a range in both rows and columns. This is similar to how a range of items are selected in a list. For ranging as a guide remember this

[**begrow**(*included*):**endrow**(*excluded*) , **begcolums**(*included*):**endcolumn**(*excluded*)]

Let’s do an example

Input:

matrix[1:3 , 0:2]

Output:

array([[4, 5], [7, 8]])

So there you go. Try experimenting on your own to fully grasp the concept.

For official Python documentation go to:

https://docs.scipy.org/doc/numpy-1.13.0/user/basics.indexing.html