# Python Matrix Operations

Python Matrix

In this section of the Python tutorial, we will look at the introduction of the matrix in Python programming. We will perform many operations on the Python matrix using the in-built functions given in Python.

### Introduction to Python Matrix

A rectangular and two-dimensional (2-D) form of the array is called a matrix. A matrix stores data in the form of rows and columns. The matrix can store elements with any data type such as string, expressions, numerical etc. We should be clear with basic concepts of the matrix before proceeding to work on it.

• Python programming doesn't provide us built-in support for the type matrices.
• We will use the multiple lists technique to implement matrix in our Python program and work with it.

Rows in the matrix: The data elements present or arranged in the horizontal form inside a matrix are called rows of the matrix.

Columns in the matrix: The data elements present or arranged in the vertical form inside a matrix are called columns.

The total number of elements present inside a matrix is represented by (R) × (C), whereas (R) represents total rows of the matrix and (C) represents total columns of the matrix.

Matrix size is generally represented by 'Mr×c,' whereas M is matrix name, r is the number of rows, and c represents the number of columns.

### Operations in Python Matrix

When we start working with the matrix, we will learn many operations that we will perform on the Python matrix. These operations can be only be performed when we have cleared the basic concept of matrices.

In this section, we will learn and perform following operation matrices in Python:

• Subtraction of matrix
• Matrix multiplication
• Scalar product of matrix
• Cross product of matrix
• Many other operations are performed of matrices.

Getting Started with Matrices in Python:

We have learned so far that what matrices are and in which form data is stored in the matrix. Now, let's start reading data inside a matrix and working with it. Then, we will perform all the operations that applicable to the matrix in Python.

Example of the Matrix

Following is an example of what a matrix is and how data is stored in a matrix.

```[[1,2],
[7,8]]```

The above matrix is a 2×2 matrix form where we have two rows and two columns of the matrix. This matrix is storing numerical data type elements inside it. As we can see, the above matrix is actually a combination of two different lists in Python, where both lists represent two different rows of the matrix.

Creating a Matrix in Python

In Python, a matrix can be created using the nested list method. We have to define different lists and nested them together to create a single list. All elements present inside a matrix are enclosed by the square brackets ([]) and separated from each other through comma(,).

Consider the following example of a Python matrix.

Example -

```PyMatrix = [[ 'Andy',  25, 125, 625],
["Sam", 4, 8.50, 64],
[5, "Bill", 25, 47] ```

As we can see in the above matrix that:

• We have defined a matrix with PyMatrix name in our Python program.
• The size of PyMatrix is 3×4 in Python, i.e., the PyMatrix contains three different rows and four different columns in it.
• We have created this PyMatrix using the nested list method in Python.
• The first row of PyMatrix has [ 'Andy',  25, 125, 625] elements in the form of the list.
• The second row of PyMatrix contains ["Sam", 4, 8.50, 64] elements in the form of the list.
• The third row of PyMatrix has [5, "Bill", 25, 47] elements in the form of the list.
• In our defined matrix, i.e., PyMatrix, we can also see that the elements present inside it have different data types (integer, float, and string).

Reading the data from a matrix means that Python should be able to read the matrix and data that we have defined in it. The Python interpreter should be able to print the output of the matrix we have defined.

Let's consider an example how a Python interpreter reads the data from the matrix we have defined in our Python program.

Example:

```# define a Python matrix with data elements in it
PyMatrix = [[ 'Andy', 25, 125, 625],
["Sam", 4, 8.50, 64],
[5, "Bill", 25, 47]]
# print the matrix so that Python interpreter will read data from this PyMatrix
print("The matrix we defined in our program is: ", PyMatrix) ```

Output:

`The matrix we defined in our program is:  [['Andy', 25, 125, 625], ['Sam', 4, 8.5, 64], [5, 'Bill', 25, 47]]`

Explanation:

In the above code, we have defined a Python matrix and named it PyMatrix. Inside PyMatrix, we have inserted data elements with different data types. The PyMatrix is of 3×4 size. After that, we printed the PyMatrix as output so that the Python interpreter will able to read data from PyMatrix.

Reading the last element from each row of PyMatrix

In the above code, we have defined a PyMatrix and printed the output. Now, we will print the last element from each row of the PyMatrix. The Python interpreter will give us the output as the last data element of each row.

Example -

```# write the Python matrix i.e., PyMatrix that we have defined above
PyMatrix = [[ 'Andy', 25, 125, 625],
["Sam", 4, 8.50, 64],
[5, "Bill", 25, 47]]
# define the length of the PyMatrix
matrix_length = len(PyMatrix)
# Now we will print the last element from each row of PyMatrix using length of matrix
for k in range(matrix_length):
print(PyMatrix[k][-1]) ```

Output:

``` 625
64
47 ```

Explanation

In the above code, we defined the length of the PyMatrix. Then, we used the length of PyMatrix to print the last element from each row of PyMatrix. We used the for loop for printing the last element as the Python output.

We can read and print data elements from any row and column in a Python matrix using this method.

### Python Matrix Operations

As we have discussed earlier, what operations we can perform on a matrix using Python. Now, we will look at each of the operations and understand how they are performed on the matrix.

Adding two or more matrices means that we will define two or matrices and add the data elements present in them. Then, we will assign the added value of matrices to a third Python matrix. In Python, we can add the data elements of matrices only if they are same data type. So before adding matrices, we should check that the data elements present in them are of the same data type.

Let's see an example of the addition of matrices in Python.

Example: In the following example, we will define two matrices, and then we add them using the nested for loop.

Example -

```# define two matrices with same data type elements in them
matrix1 = [[10, 13, 44],
[11, 2, 3],
[5, 3, 1]]
matrix2 = [[7, 16, -6],
[9, 20, -4],
[-1, 3 , 27]]
# define a third matrix with 0 elements in it and of same size.
matrix3 = [[0,0,0],
[0,0,0],
[0,0,0]]
# define the length of the matrix
matrix_length = len(matrix1)
# for adding matrix1 and matrix2 matrices use the nested for loop
for m in range(len(matrix1)):
for n in range(len(matrix2)):
matrix3[m][n] = matrix1[m][n] + matrix2[m][n]
#To Print the addition of matrix1 and matrix2
print("The sum of Python matrices matrix1 and matrix2 = ", matrix3) ```

Output:

`The sum of Python matrices matrix1 and matrix2 =  [[17, 29, 38], [20, 22, -1], [4, 6, 28]]`

Explanation:

In the above code, we have defined three matrices of same size. The first two matrices have same data type elements and third matrix have 0 elements in it. Then, we defined the length of the matrix to use for loop on it.

Then, we used the nested for loop in our program for the addition of matrix1 and matrix2. After addition, we assigned the value of data element to matrix3. After that, we printed the sum of these two matrices as matrix3 after assigning value of elements to it.

Multiplication of Two Matrices in Python:

The next operation we are going to perform on the Python matrix is the multiplication of two matrices in our Python program. Multiplication of two matrices in Python means that first, we will have to define two matrices as like in the above code. Then, we will define the third matrix in our Python program with 0 elements. The third matrix will store the result value after the multiplication of the first two matrices.

Following are the points that we should consider before proceeding with the multiplication of matrices in Python:

• The elements present in the two matrices that should be the same data type.
• The size of the two matrices should be the same.
• The third matrix where we are going to store the result value should have the same size also.
• Multiplication of matrices in Python is very similar to the addition of matrices. We only need to change the addition (+) operator to the multiplication (*) operator.

Example: Take the Python program from the addition of matrices example given above. Use the multiplication operator (*) instead of the addition (+) operator in the nested for loop.

```# define two matrices with same data type elements in them
matrix1 = [[10, 13, 44],
[11, 2, 3],
[5, 3, 1]]
matrix2 = [[7, 16, -6],
[9, 20, -4],
[-1, 3 , 27]]
# define a third matrix with 0 elements in it and of same size.
matrix3 = [[0,0,0],
[0,0,0],
[0,0,0]]
# define the length of the matrix
matrix_length = len(matrix1)
# for adding matrix1 and matrix2 matrices use the nested for loop
for m in range(len(matrix1)):
for n in range(len(matrix2)):
matrix3[m][n] = matrix1[m][n] * matrix2[m][n]
#To Print the addition of matrix1 and matrix2
print("The multiplication of Python matrices matrix1 and matrix2 = ", matrix3) ```

Output:

```The multiplication of Python matrices matrix1 and matrix2 =
[[70, 208, -264], [99, 40, -12], [-5, 9, 27]]```

Explanation: In the above program and given output we can see that:

• All the three matrices we have defined in our Python program are of same size i.e., 3×3 for each.
• We have defined elements with the same data types in matrix1 and matrix2.
• The third matrix, i.e., matrix3, has 0 data elements in it.
• We have defined the length of the matrix with matrix1 as all of them are of the same size.
• Then we used the nested for loop for multiplication of matrices with the length of the matrix.
• The outer for loop passed the control to the inner for lop for multiplying data elements present inside two matrices, i.e., matrix1 and matrix2.
• In the nested for loop, the outer for loop will iterate the matrix1 from our Python program.
• The matrix2 will be iterated by the inner for loop.
• In the iteration, each element from matrix1 and matrix2 are multiplied to each other until all the data elements of both matrices are multiplied.

Transpose Operation on Python matrix:

When the row of the matrix is converted into the columns and columns of the matrix are converted into its rows; thus, such kind of operation is called the transpose of a matrix.

In Python, when we perform transpose operation on matrix defined in our program, we should always remember the following points:

• We always need two Python matrices for performing transpose operation on one of them.
• For doing a transpose operation on the Python matrix, we should define another matrix with 0 data elements in it.
• If the size of the first matrix is m×n, then another matrix should be of n×m size (As we are changing rows into columns and columns into rows).
• We have to perform nested for loop for transpose of matrix throughout the program.
• The output of the transpose matrix is also performed with the help of for loop used with the print statement.

Let's see an example of how we can perform transpose operation on the matrix defined in our Python program.

Example: Look at the following code:

```# A Python program to perform transpose operation on a matrix using a nested for loop
matrix1 = [[21,9],
[7 ,12],
[31 ,71]]
# define a matrix with 0 elements where we will store the data values of matrix1
transmatrix = [[0,0,0],
[0,0,0]]
# iteration done through the rows of matrix
for m in range(len(matrix1)):
# iteration done through the columns of matrix
for n in range(len(matrix1)):
transmatrix[n][m] = mat1[m][n]
for r in transmatrix:
print(r) ```

Output:

```[21, 7, 31]
[9, 12, 71]```

Explanation: From the above given code and output we can see that:

• We have defined two matrices in our program.
• The size of the first matrix is 3×2, and the size of the second matrix is 2×3
• We have initialized matrix 2 with 0 elements in it. The Matrix 2 will store the transpose matrix value of matrix 1.
• We have applied nested for loops for performing transpose operation.
• The outer for loop will perform iteration on rows on matrix 1.
• The inner for loop will perform iteration on columns of matrix 1.
• Then we transferred control to matrix 2 so that it will be able to store data elements in it.
• We used another for loop for printing the transpose value of matrix 1, which is matrix 2.
• The value of matrix1[m][n]= transmatrix[n][m].

Transpose Operation on Python Matrix using List Comprehension:

We will perform a transpose operation on the Python matrix using the list comprehension method. In this method, we have to perform basics the same as in the above method.

• We will define two matrices in our Python program, i.e., The first matrix which has to be transposed and the second matrix where we will store the transpose value of the matrix first.
• The size of the first matrix should be m×n, and the second matrix should be n×m.
• The second matrix should be defined with 0 elements.
• We will use only one for loop for transposing the first matrix.
• We will print the transpose matrix using for loop.

Benefit of List Comprehension method

The benefit of using the list comprehension method for transpose a matrix is that this method reduces lines of code in our program. We have to write only one line of code for performing the transpose of the matrix. It will save our time for performing operation and writing program in our Python console.

Example: Define the matrix the same as we defined in the above code and use the line comprehension method on the matrix first. Print the output using for loop in the example.

```# A Python program to perform transpose operation on a matrix using a nested for loop
matrix1 = [[21,9],
[7 ,12],
[31 ,71]]
# define a matrix with 0 elements where we will store the data values of matrix1
transmatrix = [[0,0,0],
[0,0,0]]
# use the list comprehension method on matrix1 and with nested for loop perform transpose operation on matrix1
transmatrix = [[matrix1[n][m] for n in range(len(matrix1))] for m in range(len(matrix1))]
# now print the transpose of matrix1 i.e., transmatrix with the for loop
for r in transmatrix:
print(r) ```

Output:

```[21, 7, 31]
[9, 12, 71]```

Explanation:

The line comprehension method for transpose of matrix uses the nested for loop in a single line and saves time for writing program. This program runs in the same way as it runs in the above program.

Take Matrix as Input Data from the User

Sometimes, we need to take the matrix as input data from the user. So far, we have used a pre-defined matrix in our Python program. But now, we will build the program where the user will give us the input and then we will perform the operation on that matrix.

Before taking any matrix as user input and performing an operation on it, we have to consider the following points:

• The user can also define the size of the matrix as input.
• Users have to give all the data elements given the size of the matrix.
• We can restrict the user to give a specific data type element for a given element.
• The operation on the user input matrix depends upon the size of the matrix as well as the data type of elements present inside the matrix.

Let's look at an example of a Python matrix where we take user input.

Example: Look at the following code:

```# An example of Python matrix where we will take input from the user
rows = int(input("Enter the total number of rows you want in Python matrix:"))
columns = int(input("Enter the total number of columns you want in Python matrix:"))
# Initialize an empty matrix to store user defined values in it
matrix1 = []
print("Enter the data element entries for your Python matrix row wise:")
# Nested For used for taking the user input
for i in range(rows):       # A outer for loop used for the entries in the rows of matrices
a =[]
for j in range(columns):     # A outer for loop used for the entries in the columns of matrices
a.append(int(input()))
matrix1.append(a)
# Another nested for loop used for printing the matrix with user input data
for i in range(rows):
for j in range(columns):
print(matrix1[i][j], end = " ")
print() ```

Output:

```Enter the total number of rows you want in Python matrix:3
Enter the total number of columns you want in Python matrix:4
Enter the data element entries for your Python matrix row wise:
12
21
13
31
14
41
15
51
61
71
81
91
12 21 13 31
14 41 15 51
61 71 81 91 ```

Explanation:

1. From the above code, we can see that:

We have defined the print statement with the input function from where we will take the size of the matrix as input from the user. Then we initialized an empty matrix in the program with not actual size.

• We have used the nested for loop in the program for defining the elements of the matrix.
• The outer for loop performs iteration on the rows of the matrix.
• The inner for loop performs iteration on the columns of the matrix.
• We have used another nested for loop for printing the output.
• We have printed the output of the program using the for loop with the print statement.

2. From the output of the above program, we can see that:

• As the input function has asked us the total number of rows, we have given the value 3.
• We have defined four columns for the matrix by giving the size of the column as 4 in the input function.
• Then, we have given every single data element row-wise we want in our matrix.
• Python printed the matrix with the data and size we have given as input.

Using the Numpy and map() function in the Python Matrix:

As we have discussed earlier, Python doesn't have in-built support for the matrix, but it uses the Python list method to define matrix in our program. We can provide support of the matrix by using external libraries in our Python program.

Numpy is an external library for Python programs. Numpy library is used for scientific computation with Python programming. Numpy library provides support for the Python matrix with some functions given in the library.

• Numpy library is used for creating the input value matrices for the Python program.
• We will learn how to import the Numpy library in our Python program.
• We will also learn how to install the Numpy library in our Python console and build matrices with it.

### Installing the Numpy library:

To use the Numpy library in our Python programs, we first need to install the Numpy library through the command prompt. The Numpy library will be installed in our system with the help of the following command:

`pip install Numpy`

The above command will successfully install the Numpy library.

Importing Numpy Library in Python program:

When the Numpy library is successfully installed in our system, we write the following line of code to import the Numpy.

`import Numpy as np`

The above line of code will import the Numpy library in our Python program successfully.

Creating a Python Matrix using the Numpy Library:

Like the traditional way of defining matrices in our Python program, we can also use the Numpy library. The Numpy library helps us to work with the arrays in Python program. With the help of arrays present in our Python program, we can define a matrix.

Let's understand this through an example.

Example:

```import numpy as np
matrix1 = np.array([[21, -7, 15], [14, -9, 27], [4, -5, 20]])
print("The Python matrix we defined with numpy method is: ")
print(matrix1) ```

Output:

```The Python matrix we defined with numpy method is:
[[21 -7 15]
[14 -9 27]
[ 4 -5 20]] ```

Explanation:

In the above code, we can see that we have imported the Numpy library in our Python program. Then we have defined the Python matrix with the name matrix1 using the Numpy library. We have used the array method for matrix1. Then we printed the matrix1 as output using the print statement.

Matrix Operations using Numpy Library on Python Matrix:

Like all matrix operations that we can perform using the list method on Python matrix, same we can perform the same by importing the Numpy library in our Python program. The all-matrix operations using the Numpy library can be performed with numpy.array() function.

Following are the operations that we are going to perform using the Numpy library in this section of the Python matrix:

• Matrix subtraction
• Matrix multiplication
• Slicing of a matrix
• Printing single row or/and column of matrix etc.

Addition of Two Matrices using Numpy library:

In the addition operation, we will create two matrices using the numpy.array() function. The data elements of the two matrices should be of the same data type. We will add the two matrices using the addition (+) operator within the matrices. Then we will assign the added value to a third matrix and print the output with the third matrix.

Example: let's understand the addition of two matrices with the following Python program:

```import numpy as np
# define two matrices with same data element and of same size
matrix1 = np.array([[4, 5, 7], [2, -11, 7], [12, 13, 23]])
matrix2 = np.array([[7, -10, 24], [14, 26, 31], [17, -29, 30]])
# use addition operator on matrix1 and matrix2
matrix3 = matrix1 + matrix2
print("The matrix addition of matrix1 and matrix2 is: ")
# print the matrix 3 as output for addition of matrix 1 and matrix2
print(matrix3) ```

Output:

```The matrix addition of matrix1 and matrix2 is:
[[ 11  -5  31]
[ 16  15  38]
[ 29 -16  53]] ```

Explanation

In the above code, we have used numpy.array to define matrices. Then we have defined two matrices of same size and same data type elements. Then we used the addition operator on these two matrices and store the result value in third matrix. Then we printed the third matrix as output.

Multiplication of Two Matrices using Numpy library:

For the multiplication of two matrices, we will use the numpy.dot() function in our Python program. The numpy.dot() function performs dot multiplication between the given two matrices. It handles matrix1 and matrix2 as an array and performs multiplication operations on them.

The procedure of multiplication of two matrices is the same as of addition of two matrices except for using the numpy.dot() function.

Example: Look at the following Python program:

```import numpy as np
# define two matrices with same data element and of same size
matrix1 = np.array([[4, 5, 7], [2, -11, 7], [12, 13, 23]])
matrix2 = np.array([[7, -10, 24], [14, 26, 31], [17, -29, 30]])
# use multiplication operator on matrix1 and matrix2 with numpy.dot() function
matrix3 = matrix1.dot(matrix2)
print("The matrix multiplication of matrix1 and matrix2 is: ")
# print the matrix 3 as output for dot multiplication of matrix 1 and matrix2
print(matrix3) ```

Output:

```The matrix multiplication of matrix1 and matrix2 is:
[[ 217 -113  461]
[ -21 -509  -83]
[ 657 -449 1381]] ```

Slicing of a Matrix:

We can perform the slice operation on the Python matrix using the Numpy library imported in our Python program. The slicing of elements of the Python matrix is very similar to slicing elements present in Python standard lists.

• Slicing operation returns the element based on the start or end of the index that we have defined in our function.
• We can also perform the negative slicing on elements present in a Python matrix.

Syntax for slicing of the matrix:

Following is the syntax that we need to use while slicing elements present inside a Python matrix:

`arr[start: end]`

Explanation: In the above syntax,

• The 'arr' represents the name of the matrix on which slice operation is performing.
• By default, in the syntax, the start of the index for slicing is 0. For example: [:4] this will slice the elements from 0 to 3 and print the sliced elements.
• If we do not provide the defined end of the slicing, This function will consider the length of the array for the value to end slicing.
• We can also pass the negative index value in this syntax for both the starting and ending index.

Let's see an array example first to understand how slicing operation is performed in a Python program.

Example:

```import numpy as np
# define an array with list of elements
array1 = np.array([11,43,65,17,28,19,27,36,67,45,29])
print(array1[3:7]) # This syntax will print the elements of array from index 3 to index 7
print(array1[:6]) # This syntax will print the elements from index 0 to index 6 in our array
print(array1[4:]) # This syntax will print the elements from index 4 to the total length of the array ```

Output:

```[17 28 19 27]
[11 43 65 17 28 19]
[28 19 27 36 67 45 29] ```

Explanation –

From the above output we can see that slicing operation will perform the slicing of elements on defined index in array and print the sliced elements from the array.

Slicing Elements from Python Matrix without using Numpy

Now, let's move to the slicing of the element from a Python matrix. The slicing of elements in the Python matrix is very similar to that of Python array slicing that we have performed above.

To perform the slicing operation on elements of Python matrix, the following syntax should with the matrix:

`Matrix1[row_start:row_end, col_start:col_end]`

Explanation: In the above syntax, we can see that:

• The first part represents the start of the index from the rows and the ending index from the rows.
• The second part represents the start of an index from the columns and the ending of the index from the columns.
• 'Matrix1' represents the name of the matrix on which we will perform slice operation.

Let's see an example of performing a slicing operation on a Python matrix.

Example: We will perform slicing operation on following Python matrix:

```matrix1 = np.array([[42, 70, 63, 17, 23],
[25, 17, 29, -17, 31],
[13, 87, 45, 27, -70],
[76, -17, 25, 49, 16]]) ```

We have defined a matrix1 in Python program using the numpy library. The matrix1 consists of 4 rows with the index from 0 to 3. The 0th index row has [42, 70, 63, 17, 23] elements and 3rd indexed row has [76, -17, 25, 49, 16] elements. The matrix1 have total of five columns in it with index 0 to 4. The first column has 0th index and last column have 4th index.

Let's perform slicing operation on the matrix1 we have defined above.

```import numpy as np
# define the matrix1
matrix1 = np.array([[42, 70, 63, 17, 23],
[25, 17, 29, -17, 31],
[13, 87, 45, 27, -70],
[76, -17, 25, 49, 16]])
print("The sliced elements from matrix1 are: ")
# perform slice operation on matrix1
print(matrix1[1:3, 1:4]) # This operation will print row 1 to 3 and column 2 to 4 ```

Output:

```The sliced elements from matrix1 are:
[[ 17  29 -17]
[ 87  45  27]] ```

Explanation: In the above example, we have performed slicing on matrix1 in the print statement. We have used the slice operation to print row 1 to 3 and column 2 to 4 of the matrix1.

Some Other Operations

We can do many operations and tasks using the slicing of the matrix. We will see the following two examples to see how we can print rows, columns separately.

Example 1: Printing the first row and all columns of the matrix1 using slice operation.

```import numpy as np
# define the matrix1
matrix1 = np.array([[42, 70, 63, 17, 23],
[25, 17, 29, -17, 31],
[13, 87, 45, 27, -70],
[76, -17, 25, 49, 16]])
# use slice operation to print first row and all column elements of first row from matrix1
print(matrix1[:1, ]) ```

Output:

`[[42 70 63 17 23]]`

Example 2: Printing all rows of matrix1 separately

```import numpy as np
# define the matrix1
matrix1 = np.array([[42, 70, 63, 17, 23],
[25, 17, 29, -17, 31],
[13, 87, 45, 27, -70],
[76, -17, 25, 49, 16]])
print(matrix1) # it will print first row
print(matrix1) # it will print second row
print(matrix1[-2]) # -2 will print the last second row
print(matrix1[-1]) # -1 will print the last row ```

Output:

```[42 70 63 17 23]
[ 25  17  29 -17  31]
[ 13  87  45  27 -70]
[ 76 -17  25  49  16] ```

Conclusion

Python matrix is a specialized two-dimensional structured array. The Python matrix elements from various data types such as string, character, integer, expression, symbol etc. Python matrix can be defined with the nested list method or importing the Numpy library in our Python program. We can perform various matrix operations on the Python matrix.