# Learn Python – Python Matrix- Basic and advance

In this article, we will introduce the Matrix with Python. We will put in force every operation of matrix the usage of the Python code.

Introduction

A matrix is a rectangular 2-dimensional array which stores the data in rows and columns. The matrix can save any data type such as number, strings, expressions, etc. We have to be acquainted with the fundamental principles of matrix earlier than the use of it. The facts is organized in horizontal known as rows, and vertical preparations are columns. The variety of factors inner a matrix is (R) X (C), where R is rows and C, columns. Python would not have a built-in type for matrices so that we will use the a couple of lists as matrices.

We will learn the following operations which are utilized to the matrices.

Matrix Subtraction

Matrix Multiplication

Scalar Product

Cross Product

Many other operations

## Working of Matrices

The below matrix is 2×2, which means it has two rows and two columns.

``````[[2,4],
[5,6]]
``````

## Creating a Matrix in Python

We can create matrix in Python the use of the nested list. All elements are enclosed with the square brackets ([]) and separated by using the comma. Let’s see the following examples.

``````matrix = [[ 'Arun',  25, 90, 74],
["Sachin", 410, 87.50, 130]
[56, "Abhinay", 253, 471]
``````

We have created a 3×3 matrix using the nested list.

The first row contains [‘Arun’, 25, 90, 74] in the list form.

The second row contains [‘Sachin’, 410, 87.50, 130] in the list form.

The third row contains [56, “Abhinay”, 253, 471] in the list form.

We notice that our matrix consists of numbers as well as a string value.

In the following example, we will read every row of the described matrix.

Example –

``````matrix = [[ 'Arun',  25, 90, 74],
['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]

print("The matrix is: ", matrix)
``````

Output:

``````The matrix is:  [['Arun', 25, 90, 74], ['Sachin', 410, 87.5, 130], [56, 'Abhinay', 253, 471]]
``````

Read the Last Element from each row

In the following example, we will examine the closing element of the each row using the Python program.

Example –

``````matrix = [[ 'Arun',  25, 90, 74],
['Sachin', 410, 87.50, 130],
[56, 'Abhinay', 253, 471]]

matrix_length = len(matrix)

#To read the last element from each row.
for i in range(matrix_length):
print(matrix[i][-1])
``````

Output:

``````74
130
471``````

Explanation –

In the above code, we have created a matrix, and we get the size of the matrix. We iterated each row the usage of for loop and printed the result.

We can examine any row or column the usage of the above method.

Let’s understand the following operation of the matrix.

We will add the two matrices and using the nested for loop through the given matrices.

Example –

``````mat1 = [[10, 13, 44],
[11, 2, 3],
[5, 3, 1]]

mat2 = [[7, 16, -6],
[9, 20, -4],
[-1, 3 , 27]]

mat3  = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(mat1)

#To Add mat1 and mat2 matrices
for i in range(len(mat1)):
for k in range(len(mat2)):
mat3[i][k] = mat1[i][k] + mat2[i][k]

#To Print the matrix
print("The sum of Matrix mat1 and mat2 = ", mat3)
``````

Output:

``The sum of Matrix M1 and M2 =  [[17, 29, 38], [20, 22, -1], [4, 6, 28]]``

Explanation –

The first and second matrices are 3X3.

We initialized another matrix mat3, which will store the resultant matrix.

We applied nested for loop to iterate the matrices, the outer loop iterate on the first matrix.

The control transfers the inner loop; and it iterated to the second inner loop, here the value of i is zero, and k is also zero.

In the first iteration, the first element of the mat1 and mat2 added to each other will continue until all elements are added.

## Multiplication of Two Matrices

Multiplication of the two matrices is the same as the above code, and solely we want to exchange the operator + to *. Let’s recognize the following example.

Example –

``````mat1 = [[10, 13, 44],
[11, 2, 3],
[5, 3, 1]]

mat2 = [[7, 16, -6],
[9, 20, -4],
[-1, 3 , 27]]

mat3  = [[0,0,0],
[0,0,0],
[0,0,0]]
matrix_length = len(mat1)

#To Add mat1 and mat2 matrices
for i in range(len(mat1)):
for k in range(len(mat2)):
mat3[i][k] = mat1[i][k]  * mat2[i][k]

#To Print the matrix
print("The sum of Matrix mat1 and mat2 = ", mat3)
``````

Output:

``The sum of Matrix mat1 and mat2 =  [[70, 208, -264], [99, 40, -12], [-5, 9, 27]]``

## Transpose of Matrix

A transpose is an operation the place the given matrix’s row is transformed into a column and vice-versa. Let’s recognize the following example.

Example –

``````# Program to transpose a matrix using a nested loop

mat1 = [[12,7],
[4 ,5],
[3 ,8]]

res = [[0,0,0],
[0,0,0]]

# iterate through rows
for i in range(len(mat1)):
# iterate through columns
for j in range(len(mat1[0])):
res[j][i] = mat1[i][j]

for r in res:
print(r)
``````

Output:

``````[12, 4, 3]
[7, 5, 8]``````

Explanation

In the above code, we have two for loop to iterate thru each row and every column. As we can see that in above output, we assigned the mat1[i][j] and res[j][k].

## Transpose Matrix Using List Comprehension

We can use the list comprehension to transpose a matrix with one line of code. Let’s apprehend the following example.

Example –

``````mat1 = [[12,7],
[4 ,5],
[3 ,8]]

res = [[0,0,0],
[0,0,0]]

res = [[mat1[j][i] for j in range(len(mat1))] for i in range(len(mat1[0]))]

for r in res:
print(r)
``````

Output:

``````[12, 4, 3]
[7, 5, 8]``````

The output is the same as above. The listing comprehension decreased the traces of code and transposed the matrix.

## Take Matrix Input from the User

We have mentioned the pre-defined matrices so far. But what if consumer desires to enter their data. So we are defining the following example of a user-defined matrix.

Example –

``````# A example for matrix input from user
row = int(input("Enter the number of rows:"))
column = int(input("Enter the number of columns:"))

# Initialize empty matrix
matrix = []
print("Enter the entries row wise:")

# For user input
for i in range(row):       # A outer for loop for row entries
a =[]
for j in range(column):     # A inner for loop for column entries
a.append(int(input()))
matrix.append(a)

# For printing the matrix
for i in range(row):
for j in range(column):
print(matrix[i][j], end = " ")
print()
``````

Output:

``````Enter the number of rows:3
Enter the number of columns:3
Enter the entries row wise:
5
6
7
8
9
2
4
3
1
5 6 7
8 9 2
4 3 1``````

Explanation –

In the above code, we have taken the enter from the person to enter number of rows and columns. We have entered the 3 rows and three columns; it capacity the matrix will have 9 elements. In for loop, the elements are inserted to the empty matrix using the append () function. The second for is loop used to print enter data in the matrix format.

Using the Numpy and map() function

Python presents the exterior library Numpy. It is used for scientific computation; we will study Numpy with matrix in under section. We will use it for the consumer input matrix.

Example –

## Creating Matrix Using Numpy Library

The Numpy library helps us to work with the array. To work with the Numpy, we want to set up the Numpy the usage of the following command.

``````pip install Numpy
``````

After a successful installation, we have to import it into our program.

``````import numpy as np
``````

Let’s understand the following example.

Example –

``````import numpy as np
mat1 = np.array([[10, -5, 15], [30, -6, 91], [2, 8, 7]])
print("The matrix is: ")
print(mat1)
``````

Output:

``````The matrix is:
[[10 -5 15]
[30 -6 91]
[ 2  8  7]]``````

## Matrix Operation Using Numpy

We can function all matrix operation the usage of the numpy.array() such as addition, subtraction, transpose, slicing the matrix, etc.

We will create two matrices the usage of the numpy.array() characteristic and add them the use of the + operator. Let’s apprehend the following example.

Example –

``````import numpy as np
mat1 = np.array([[7, 8, 9], [3, -1, 17], [15, 10, 21]])
mat2 = np.array([[9, -18, 27], [11, 22, 33], [13, -26, 39]])
mat3 = mat1 + mat2
print(mat3)
``````

Output:

``````The matrix addition is:
[[ 16 -10  36]
[ 14  21  50]
[ 28 -16  60]]``````

Matrix Multiplication

We will use the mumpy.dot() technique to multiply each matrices. It is a dot multiplication of the matrix mat1 and mat2 and handles the 2D array and performs multiplication. Let’s understand the following example.

Example –

``````import numpy as np
mat1 = np.array([[4, 6], [5, 10]])
mat2 =  np.array([[3, -1], [11, 22]])
mat3 = mat1.dot(mat2)
print("The matrix is:")
print(mat3)
``````

Output:

``````The matrix is:
[[ 78 128]
[125 215]]``````

Slicing of a Matrix

We can slice the matrix’s aspect as we do in the Python widespread list. Slicing returns the component based totally on the start/end index. We can also the bad slicing. The syntax is given below.

Syntax –

``````arr[start: end]
``````

The arr represents the matrix name. By default the begin index is 0, for instance – [:3], it skill start index is zero If we do now not provide the price to end, it will consider the length of the array. We can pass terrible index values to both start and end. In the following example, we will follow reducing in regular array to apprehend how cutting works.

Example –

``````import numpy as np

arr = np.array([10,40,61,14,25,12,97])
print(arr[2:5]) # It will print the elements from 2 to 4
print(arr[:4]) # It will print the elements from 0 to 3
print(arr[3:]) # It will print the elements from 3 to length of the array.
``````

Output:

``````[61 14 25]
[10 40 61 14]
[14 25 12 97]``````

Now, we will put into effect reducing on matrix. To perform the reducing on matrix, comply with the below syntax.

Mat1[row_start:row_end, col_start:col_end]

In the above syntax –

The first start/end represents the rows that mean select the rows of the matrix.

The first start/end represents the columns that mean select the column of the matrix.

We will perform slicing in the below matrix.

``````mat1 = np.array([[4, 10, 60, 18, 20],
[35, 16, 19, -12, 41],
[23, 80, 42, 24, -20],
[7, -10, 15, 40, 17]])
``````

The above matrix consists of 4 rows. The 0th uncooked has [4, 10, 60, 18, 20], 1st row has [35, 16, 19, -12, 41] and so on. It has 5 columns. Let’s apprehend the following example.

Example –

``````import numpy as np
mat1 = np.array([[4, 10, 60, 18, 20],
[35, 16, 19, -12, 41],
[23, 80, 42, 24, -20],
[7, -10, 15, 40, 17]])
print(mat1[1:3, 1:4])
``````

Output:

``````[[ 16  19 -12]
[ 80  42  24]]``````

Explanation

In the above example, we have printed the first and 2nd rows, and we sliced the first, second, and 1/3 columns. According to the reducing syntax, we can get any rows and columns.

Example – Print first row and all columns

``````import numpy as np
mat1 = np.array([[4, 10, 60, 18, 20],
[35, 16, 19, -12, 41],
[23, 80, 42, 24, -20],
[7, -10, 15, 40, 17]])
print(mat1[:1, ])
``````

Output:

``[ 4 10 60 18 20]]``

Example – Print rows of the matrix

``````import numpy as np
mat1 = np.array([[14, 60, 29], [35, -10, 13], [4,8,12]])
print(mat1[0])  #first row
print(mat1[1]) # the second row
print(mat1[-1]) # -1 will print the last row
``````

Output:

``````[14 60 29]
[ 35 -10  13]
[ 4  8 12]``````

## Conclusion

We have mentioned primary matrix the use of Python so far. We have learned to create matrix using a exceptional approaches. Python matrix is a specialized two-dimensional rectangular list of data. The matrix can consist of a number, strings, expression, symbols, etc. Python does not furnish a direct way to enforce the matrix data type. We can create the matrix the use of the nested listing and Numpy library.