A Python matrix is a special case of a two-dimensional rectangular array of data stored in rows and columns. The data in a matrix can be numbers, strings, expressions, symbols, and each data element is of the strictly same size. Matrices are important data structures used in mathematical and scientific calculations.
Making a Matrix in Python
Example 1 of a Matrix
A record of daily temperatures can be recorded in a matrix. If we record daily temperatures in the morning and evening for one week, we can create a 7X3 (Seven by Three Matrix) matrix using an array.
from numpy import * a = array([['Mon',17,15],['Tue',11,18], ['Wed',15,19], ['Thu',11,19], ['Fri',15,22],['Sat',12,18], ['Sun',13,13]]) m = reshape(a,(7,3)) print(m)
The above temperature records can be represented as a two-dimensional array as below.
[['Mon' '17' ‘15’]
['Tue' '11' '18']
['Wed' '15' '19']
['Thu' '11' '19']
['Fri' '15' '22']
['Sat' '12' '18']
['Sun' '13' '13']]
Example 2 of a Matrix
Example two will involve representing three students and the subjects they study using a two-dimensional array, which we call a matrix. Below is the illustration of the student’s matrix.
StudentID | StudentName | Subjects |
100DAN | Jonathan moss | ENGLISH |
200DAN | Joy Wembley | MATH |
300DAN | Ruth Mersey | COMPUTER |
Python can represent the three by three matrixes in terms of lists. In the example below, student_val is a representation of the 3 * 3 matrix of students’ information with three rows and three columns.
student_val = [[‘100DAN ‘,’ Jonathan moss ‘, ‘ ENGLISH ‘], [‘200DAN ‘, ‘ Joy Wembley ‘ , ‘ MATH ‘], [‘300DAN ‘, ‘ Ruth Mersey ‘ , ‘ COMPUTER’]]
Creation of Matrices in Python
Python uses nested lists to create a matrix in Python. Nested lists arise when many individual lists are grouped using commas to separate them. A single list is enclosed within the square brackets ‘[‘and ‘].’ Using our case of the student’s matrix, the resultant matrix from nesting lists is as follows:
Dynamic creation of a Matrix in Python
In Python, we can easily create a dynamic x by y matrix. The implementation involves listing elements’ set, which is x in this case, and then subsequently making every one of the elements to be connected to another 1D list whose elements is y. The implementation of this concept is illustrated below.
x = 3 y = 3 val_result = [0] * x for i in range (x): val_result [i] = [0] * y print(val_result)
The resultant output of this function is:
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
How to Access Elements of a Matrix
We illustrate two ways to access elements of a matrix in Python, namely using negative indexing and list index.
Negative Indexing
In Python, -1 point to the last element in a matrix, -2 is the second last, and the sequence continues. This concept of accessing values using negative indices in square brackets is called negative indexing.
Using our student’s example,
student_val = [['100DAN ',' Jonathan moss ', ' ENGLISH '], ['200DAN ', ' Joy Wembley ' , ' MATH '], ['300DAN ', ' Ruth Mersey ' , ' COMPUTER']] print(student_val [-1]) print(student_val [-2][-2])
The output
['300DAN ', ' Ruth Mersey ' , ' COMPUTER']
Joy Wembley
List Index
Here, you pass rows and columns to square brackets immediately after the variable name like student_val in our example. The final formation should be student_val[row_val][col_val]
student_val = [['100DAN ',' Jonathan moss ', ' ENGLISH '], ['200DAN ', ' Joy Wembley ' , ' MATH '], ['300DAN ', ' Ruth Mersey ' , ' COMPUTER']] print(student_val [0]) print(student_val [1][0])
Output
['100DAN ',' Jonathan moss ', ' ENGLISH ']
200DAN
How do Matrices work?
Step A
11 | 12 |
13 | 14 |
The table above is a 2X2 (two by two matrix) matrix made up of two rows and two columns. The values inside are numbers. Column 1 has values 11, 13, and Column 2 has values 12, 14. Row 1 has values 11,12, and Row 2 has values 13,14.
Step B
1 | 2 | 3 | 4 |
2 | 3 | 4 | 5 |
3 | 4 | 5 | 6 |
4 | 5 | 6 | 7 |
The table above is a 4×4 (four by four matrix) matrix made of four rows and four columns. Row 1 has values 1,2,3,4 and row 4 has values 4,5,6,7. Column 2 has values 2,3,4,5 and column 3 has values 3,4,5,6.
In Python, you can create a matrix of nxn dimensions. Operations like addition, multiplication, subtraction, etc., can be performed on a matrix. Matrices in Python use nested list arrays to implement matrices.
Create matrix using Nested List
In Python, arrays are represented using the list data type. We will create a 3×2 matrix, as shown below:
8 | -7 |
7 | 5 |
-13 | 19 |
• The matrix has three rows and two columns.
• The first row in a list format will be:[8,-7]
• The second row:[7,5] • The third row:[-13,19]
The matrix inside a list can be represented as below:
List = [[Row1],
[Row2],
[Row3]
…
[RowN]]
The list for the 3×2 (three by two matrix) matrix we created above can be represented as follows:
N1 = [[8, -7], [7,5], [-13,19]]
Read Data in a Matrix using a List
We will use the matrix we created above to read data, print data, and access values in a matrix.
Example: To print the matrix
N1 = [[8, -7], [7,5], [-13,19]] #To print the matrix print(N1)
Output:
The matrix N1 is equal to
[[8, -7], [7,5], [-13,19]]
Example 2: Read the last element from each row.
N1 = [[8, -7], [7,5], [-13,19]] N1_length = len(N1) #To read the last element from each row. for i in range(N1_length): print(N1[i][-1])
Output:
-7
5
19
Adding Matrices Using Nested List
Given two matrices (N1, N2) in the form of a nested list, we can add them, but we must first initialize a matrix that will store the result of N1+N2.
N1:
N1 = [[8, -7],
[7,5],
[-13,19]]
N2:
N2 = [[5, -7],
[10, 15],
[5,-20]]
N3:
M3 = [[0,0],
[0,0],
[0,0]]
Adding Matrices:
N1 = [[8, -7], [7,5], [-13,19]] N2 = [[5, -7], [10, 15], [5,-20]] N3 = [[0,0], [0,0], [0,0]] matrix_length = len(N1) # To Add N1 and N2 matrices for i in range(len(N1)): for k in range(len(N2)): N3[i][k] = N1[i][k] + n2[i][k] # To Print the Matrix print("The sum of Matrix N1 and N2 = ", N3)
Output:
The sum of Matrix N1 and N2 = [[13, -14], [17, 20], [-8, -1]]
Multiplication of Matrices Using Nested List
We can utilize the for-loop on both the matrices to multiply matrices using nested lists.
N1 = [[8, -7], [7,5], [-13,19]] N2 = [[5, -7], [10, 15], [5,-20]] N3 = [[0,0], [0,0], [0,0]] matrix_length = len(N1) #To Multiply N1 and N2 matrices for i in range(len(N1)): for k in range(len(N2)): N3[i][k] = N1[i][k] * N2[i][k] # To Print the Matrix print("The multiplication of Matrix N1 and N2 = ", N3)
Output:
The multiplication of Matrix N1 and N2 = [[40, -49], [70, 75], [-65, -380]]
Create Matrices using Arrays from Python Numpy Package
Numpy package processes arrays faster in comparison to a list in Python. To use NumPy in Python, you have to install it and import it to your code.
Example: Using an array in Numpy to create a Matrix
import numpy as np N1 = np.array([[8, -7], [7,5], [-13,19]]) print(N1)
Output:
[[8, -7]
[7, 5]
[-13,19]]
Matrix operation using Numpy Array
We can make matrix operations such as addition, subtraction, transpose, multiplication, reading rows, columns, and slicing using the array() method.
Matrix Addition
Create two matrices using NumPy.array() and add them using the (+) operator.
import NumPy as np N1 = np.array([[8, -7], [7,5], [-13,19]]) N2 = np.array([[5, -7], [10, 15], [5,-20]) N3 = N1 + N2 print(N3)
Output:
[[13, -14]
[17, 20]
[-8, -1]]
Matrix subtraction
Create two matrices using NumPy.array() and add them using the (-) operator.
import NumPy as np N1 = np.array([[8, -7], [7,5], [-13,19]]) N2 = np.array([[5, -7], [10, 15], [5,-20]) N3 = N1 - N2 print(N3)
Output:
[[3, 0]
[-3, -10]
[-18, -39]]
Matrix Multiplication
To perform multiplication on matrices, create two matrices using NumPy.arary(). To multiply them, we use the NumPy dot() method. Numpy dot() is the dot product of matrix N1 and N2. Numpy. dot() handles the 2D arrays and performs matrix multiplications.
import NumPy as np N1 = np.array([[8, -7], [7,5]]) N2 = np.array([[5, -7], [10,15]]) N3 = N1.dot(N2) print(N3)
Output:
[[ -30 -161]
[ 85 26]]
Matrix Transpose
Matrix transpose entails changing columns as rows and rows as columns. We utilize the transpose() function from Numpy to find the transpose of a matrix.
import NumPy as np N1 = np.array([[8, -7], [7,5], [-13,19]]) N2 = N1.transpose() print(N2)
Output:
[[ 8 7 -13]
[ -7 5 19]]
Slicing Matrices
Slicing a matrix will return elements from the matrix based on the start and end index.
• Syntax for slicing: [start:end]
• The start index is considered 0 if the start index is not given. [:9] means [0:9]
• If the end is not specified, the array’s length will be used.
• The start/end’s negative value implies that the slicing will be done from the end of the array.
The syntax for slicing a matrix is as follows:
N1[start_row:end_row, start_col:end_col]
Example:
The example below shows how to get the rows and columns data from the matrix using slicing. In the example, we are printing the 1st and 2nd row, and for columns, we want the first, second, and third column. To get that output, we have used: N1[1:3, 1:4]
N1 = np.array([[2, 8, 6,138, 10],
[3, 2, 9, -19, -25],
[4, 18, 32, 1, -30],
[25, -18, 45, -10, 15]])
Slicing:
import NumPy as np N1 = np.array([[2, 8, 6,138, 10], [3, 2, 9, -19, -25], [4, 18, 32, 1, -30], [25, -18, 45, -10, 15]]) print(N1[1:3, 1:4]) # For 1:3, it will give the first and second rows. # The columns will be taken from first to third.
Output:
[[ 2 9 -19]
[ 18 32 1]]
Example: Print all rows and second columns
import numpy as np N1 = np.array([[2, 8, 6,138, 10], [3, 2, 9, -19, -25], [4, 18, 32, 1, -30], [25, -18, 45, -10, 15]]) print(N1[:,2]) # This will print all rows and the second column data.
Output:
[6 9 32 45]
Example: Print the first three rows and three two columns
import numpy as np N1 = np.array([[2, 8, 6,138, 10], [3, 2, 9, -19, -25], [4, 18, 32, 1, -30], [25, -18, 45, -10, 15]]) print(N1[:3,:3])
Output:
[[ 2 8 6]
[ 3 2 9]
[ 4 18 32]]
Accessing Numpy Matrix
Print rows of the Matrix
import numpy as np N1 = np.array([[8, -7], [7,5], [-13,19]]) print(N1[0]) #first row print(N1[1]) # the second row print(N1[-1]) # -1 will print the last row
Output:
[ 8 -7]
[7 5]
[-13 19]
N1[0] will give you the first row,
N1[1] will give you the second row
N1[2] or N1[-1] will give you the third row or last row.
Print columns of the matrix
import numpy as np N1 = np.array([[2, 8, 6,138, 10], [3, 2, 9, -19, -25], [4, 18, 32, 1, -30], [25, -18, 45, -10, 15]]) print(N1[:,0]) # Will print the first Column print(N1[:,3]) # Will print the third Column print(N1[:,-1]) # -1 will give you the last column
Output:
[ 2 3 4 25]
[138 -19 1 -10]
[ 10 -25 -30 15]
Recap
A matrix is a two-dimensional rectangular array of numbers, symbols, or expressions, arranged in rows and columns. Matrices are data structures that are extensively used in scientific and mathematical calculations. Python matrices are created using nested lists and by using the Numpy library. The following operations can be done on Python matrices: addition, subtraction, multiplication, transpose, reading the rows, columns of a matrix, transpose the matrix, and slicing the matrix.
Important Numpy methods to work with matrices include: numpy.array() for addition and subtraction, Numpy.dot() for multiplication, and transpose() function to calculate the transpose of a matrix.