Javatpoint Logo
Javatpoint Logo

Python Matrix

In this article, we will introduce the Matrix with Python. We will implement each operation of matrix using the Python code.

Introduction

A matrix is a rectangular 2-dimensional array which stores the data in rows and columns. The matrix can store any data type such as number, strings, expressions, etc. We must be familiar with the basic concepts of matrix before using it. The data is arranged in horizontal called rows, and vertical arrangements are columns. The number of elements inside a matrix is (R) X (C), where R is rows and C, columns. Python doesn't have a built-in type for matrices so that we will use the multiple lists as matrices.

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

  • Matrix addition
  • Matrix Subtraction
  • Matrix Multiplication
  • Scalar Product
  • Cross Product
  • Many other operations

Working of Matrices

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

Creating a Matrix in Python

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

  • We have created a 3x3 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.

Read the Matrix Data

In the following example, we will read each row of the defined matrix.

Example -

Output:

Read the Last Element from each row

In the following example, we will read the last element of the each row using the Python program.

Example -

Output:

74
130
471

Explanation -

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

We can read any row or column using the above method.

Let's understand the following operation of the matrix.

Adding two Matrices

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

Example -

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 only we need to change the operator + to *. Let's understand the following example.

Example -

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 where the given matrix's row is converted into a column and vice-versa. Let's understand the following example.

Example -

Output:

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

Explanation

In the above code, we have two for loop to iterate through each row and each 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 understand the following example.

Example -

Output:

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

The output is the same as above. The list comprehension reduced the lines of code and transposed the matrix.

Take Matrix Input from the User

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

Example -

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 input from the user to enter number of rows and columns. We have entered the 3 rows and 3 columns; it means 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 input data in the matrix format.

Using the Numpy and map() function

Python provides the external library Numpy. It is used for scientific computation; we will learn Numpy with matrix in below section. We will use it for the user input matrix.

Example -

Creating Matrix Using Numpy Library

The Numpy library helps us to work with the array. To work with the Numpy, we need to install the Numpy using the following command.

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

Let's understand the following example.

Example -

Output:

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

Matrix Operation Using Numpy

We can perform all matrix operation using the numpy.array() such as addition, subtraction, transpose, slicing the matrix, etc.

Matrix Addition

We will create two matrices using the numpy.array() function and add them using the + operator. Let's understand the following example.

Example -

Output:

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

Matrix Multiplication

We will use the mumpy.dot() method to multiply both 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 -

Output:

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

Slicing of a Matrix

We can slice the matrix's element as we do in the Python standard list. Slicing returns the element based on the start/end index. We can also the negative slicing. The syntax is given below.

Syntax -

The arr represents the matrix name. By default the start index is 0, for example - [:3], it means start index is 0. If we do not provide the value to end, it will consider the length of the array. We can pass negative index values to both start and end. In the following example, we will apply slicing in normal array to understand how slicing works.

Example -

Output:

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

Now, we will implement slicing on matrix. To perform the slicing on matrix, follow 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.

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

Example -

Output:

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

Explanation

In the above example, we have printed the first and second rows, and we sliced the first, second, and third columns. According to the slicing syntax, we can get any rows and columns.

Example - Print first row and all columns

Output:

[ 4 10 60 18 20]]

Example - Print rows of the matrix

Output:

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

Conclusion

We have discussed basic matrix using Python so far. We have learned to create matrix using a different approaches. Python matrix is a specialized two-dimensional rectangular list of data. The matrix can consist of a number, strings, expression, symbols, etc. Python doesn't provide a direct way to implement the matrix data type. We can create the matrix using the nested list and Numpy library.






Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA