Open In App

Python – Matrix

Last Updated : 06 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Here we will discuss different ways how we can form a matrix using Python within this tutorial we will also discuss the various operation that can be performed on a matrix. we will also cover the external module Numpy to form a matrix and its operations in Python.

Matrix in Python

 

What is the matrix?

A matrix is a collection of numbers arranged in a rectangular array in rows and columns. In the fields of engineering, physics, statistics, and graphics, matrices are widely used to express picture rotations and other types of transformations.
The matrix is referred to as an m by n matrix, denoted by the symbol “m x n” if there are m rows and n columns.

Creating a simple matrix using Python

Method 1: Creating a matrix with a List of list

Here, we are going to create a matrix using the list of lists.

Python3




matrix = [[1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]]
 
print("Matrix =", matrix)


Output:

Matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]

Method 2: Take Matrix input from user in Python

Here, we are taking a number of rows and columns from the user and printing the Matrix.

Python3




Row = int(input("Enter the number of rows:"))
Column = int(input("Enter the number of columns:"))
 
# Initialize matrix
matrix = []
print("Enter the entries row wise:")
 
# For user input
# A for loop for row entries
for row in range(Row):   
    a = []
    # A for loop for column entries
    for column in range(Column):  
        a.append(int(input()))
    matrix.append(a)
 
# For printing the matrix
for row in range(Row):
    for column in range(Column):
        print(matrix[row][column], end=" ")
    print()


Output:

Enter the number of rows:2
Enter the number of columns:2
Enter the entries row wise:
5
6
7
8

5 6 
7 8 

Time Complexity: O(n*n)
Auxiliary Space: O(n*n)

Method 3: Create a matrix using list comprehension

List comprehension is an elegant way to define and create a list in Python, we are using the range function for printing 4 rows and 4 columns.

Python3




matrix = [[column for column in range(4)] for row in range(4)]
 
print(matrix)


Output:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

Assigning Value in a matrix

Method 1: Assign value to an individual cell in Matrix

Here we are replacing and assigning value to an individual cell (1 row and 1 column = 11) in the Matrix.

Python3




X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
row = column = 1
 
X[row][column] = 11
 
print(X)


Output:

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

Method 2: Assign a value to an individual cell using negative indexing in Matrix

Here we are replacing and assigning value to an individual cell (-2 row and -1 column = 21) in the Matrix.

Python3




row = -2
column = -1
 
X[row][column] = 21
 
print(X)


Output:

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

Accessing Value in a matrix

Method 1: Accessing Matrix values

Here, we are accessing elements of a Matrix by passing its row and column.

Python3




print("Matrix at 1 row and 3 column=", X[0][2])
print("Matrix at 3 row and 3 column=", X[2][2])


Output:

Matrix at 1 row and 3 column= 3
Matrix at 3 row and 3 column= 9

Method 2: Accessing Matrix values using negative indexing

Here, we are accessing elements of a Matrix by passing its row and column on negative indexing.

Python3




import numpy as np
 
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
print(X[-1][-2])


Output:

8

Mathematical Operations with Matrix in Python

Example 1: Adding values to a matrix with a for loop in python

Here, we are adding two matrices using the Python for-loop.

Python3




# Program to add two matrices using nested loop
X = [[1, 2, 3],[4, 5, 6], [7, 8, 9]]
Y = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
 
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 
# iterate through rows
for row in range(len(X)):
 
    # iterate through columns
    for column in range(len(X[0])):
        result[row][column] = X[row][column]+ Y[row][column]
 
for r in result:
    print(r)


Output:

[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Time Complexity: O(n*n)
Auxiliary Space: O(n*n)

Example 2: Adding and subtracting values to a matrix with list comprehension

Performing the Basic addition and subtraction using list comprehension.

Python3




Add_result = [[X[row][column] + Y[row][column]
               for column in range(len(X[0]))]
               for row in range(len(X))]
Sub_result = [[X[row][column] - Y[row][column]
               for column in range(len(X[0]))]
               for row in range(len(X))]
 
print("Matrix Addition")
for r in Add_result:
    print(r)
 
print("\nMatrix Subtraction")
for r in Sub_result:
    print(r)


Output:

Matrix Addition
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]


Matrix Subtraction
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]

Time Complexity: O(n*n)
Auxiliary Space: O(n*n)

Example 3: Python program to multiply and divide two matrices

Performing the Basic multiplication and division using Python loop.

Python3




rmatrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 
for row in range(len(X)):
    for column in range(len(X[0])):
        rmatrix[row][column] = X[row][column] * Y[row][column]
         
print("Matrix Multiplication",)
for r in rmatrix:
    print(r)
         
for i in range(len(X)):
    for j in range(len(X[0])):
        rmatrix[row][column] = X[row][column] // Y[row][column]
 
print("\nMatrix Division",)  
for r in rmatrix:
    print(r)


Output:

Matrix Multiplication
[9, 16, 21]
[24, 25, 24]
[21, 16, 9]

Matrix Division
[0, 0, 0]
[0, 1, 1]
[2, 4, 9]

Time Complexity: O(n*n)
Auxiliary Space: O(n*n)

Transpose in matrix

Example: Python Program to Transpose a Matrix using loop

Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].

Python3




X = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
 
result = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
 
# iterate through rows
for row in range(len(X)):
    # iterate through columns
    for column in range(len(X[0])):
        result[column][row] = X[row][column]
 
for r in result:
    print(r)
     
# # Python Program to Transpose a Matrix using the list comprehension
 
# rez = [[X[column][row] for column in range(len(X))]
#    for row in range(len(X[0]))]
 
# for row in rez:
#     print(row)


Output:

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

Time Complexity: O(n*n)
Auxiliary Space: O(n*n)

Matrix using Numpy

Create a matrix using Numpy 

Here we are creating a Numpy array using numpy.random and a random module.

Python3




import numpy as np
   
# 1st argument --> numbers ranging from 0 to 9,
# 2nd argument, row = 3, col = 3
array = np.random.randint(10, size=(3, 3))
print(array)


Output:

[[2 7 5]
 [8 5 1]
 [8 4 6]]

Matrix mathematical operations in Python Using Numpy

Here we are covering different mathematical operations such as addition subtraction, multiplication, and division using Numpy.

Python3




# initializing matrices
x = numpy.array([[1, 2], [4, 5]])
y = numpy.array([[7, 8], [9, 10]])
 
# using add() to add matrices
print ("The element wise addition of matrix is : ")
print (numpy.add(x,y))
 
# using subtract() to subtract matrices
print ("The element wise subtraction of matrix is : ")
print (numpy.subtract(x,y))
 
print ("The element wise multiplication of matrix is : ")
print (numpy.multiply(x,y))
 
# using divide() to divide matrices
print ("The element wise division of matrix is : ")
print (numpy.divide(x,y))


Output:

The element wise addition of matrix is : 
[[ 8 10]
 [13 15]]
The element wise subtraction of matrix is : 
[[-6 -6]
 [-5 -5]]
The element wise multiplication of matrix is : 
[[ 7 16]
 [36 50]]
The element wise division of matrix is : 
[[0.14285714 0.25      ]
 [0.44444444 0.5       ]]

Dot and cross product with Matrix

Here, we will find the inner, outer, and cross products of matrices and vectors using NumPy in Python.

Python3




X = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
 
Y = [[9, 8, 7], [6, 5, 4],[3, 2, 1]]
 
dotproduct = np.dot(X, Y)
print("Dot product of two array is:", dotproduct)
 
dotproduct = np.cross(X, Y)
print("Cross product of two array is:", dotproduct)


Output:

Dot product of two array is: [[ 30  24  18]
 [ 84  69  54]
 [138 114  90]]
Cross product of two array is: [[-10  20 -10]
 [-10  20 -10]
 [-10  20 -10]]

Matrix transpose in Python using Numpy

To perform transpose operation in matrix we can use the numpy.transpose() method.

Python3




matrix = [[1, 2, 3], [4, 5, 6]]
print("\n", numpy.transpose(matrix))


Output:

[[1 4][2 5][3 6]]

Create an empty matrix with NumPy in Python

Initializing an empty array, using the np.zeros().

Python3




a = np.zeros([2, 2], dtype=int)
print("\nMatrix of 2x2: \n", a)
 
c = np.zeros([3, 3])
print("\nMatrix of 3x3: \n", c)


Output:

Matrix of 2x2: 
 [[0 0]
 [0 0]]

Matrix of 3x3: 
 [[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

Slicing in Matrix using Numpy

Slicing is the process of choosing specific rows and columns from a matrix and then creating a new matrix by removing all of the non-selected elements. In the first example, we are printing the whole matrix, in the second we are passing 2 as an initial index, 3 as the last index, and index jump as 1. The same is used in the next print we have just changed the index jump to 2.

Python3




X = np.array([[6, 8, 10],
    [ 9, -12, 15],
    [ 12, 16, 20],
    [ 15, -20, 25]])
 
# Example of slicing
# Syntax: Lst[ Initial: End: IndexJump ]
print(X[:])
 
print("\nSlicing Third Row-Second Column: ", X[2:3,1])
print("\nSlicing Third Row-Third Column: ", X[2:3,2])


Output:

[[  6   8  10]
 [  9 -12  15]
 [ 12  16  20]
 [ 15 -20  25]]

 Slicing Third Row-Second Column: [16]

 Slicing Third Row-Third Column: [20]

Delete rows and columns using Numpy

Here, we are trying to delete rows using the np.delete() function. In the code, we first tried to delete the 0th row, then we tried to delete the 2nd row, and then the 3rd row.

Python3




# create an array with integers
# with 3 rows and 4 columns
a = np.array([[6, 8, 10],
    [ 9, -12, 15],
    [ 12, 16, 20],
    [ 15, -20, 25]])
 
# delete 0 th row
data = np.delete(a, 0, 0)
print("data after 0 th row deleted: ", data)
 
# delete 1 st row
data = np.delete(a, 1, 0)
print("\ndata after 1 st row deleted: ", data)
 
# delete 2 nd row
data = np.delete(a, 2, 0)
print("\ndata after 2 nd row deleted: ", data)


Output:

data after 0 th row deleted: 
[[  9 -12  15]
 [ 12  16  20]
 [ 15 -20  25]]

data after 1 st row deleted: 
[[  6   8  10]
 [ 12  16  20]
 [ 15 -20  25]]

data after 2 nd row deleted: 
[[  6   8  10]
 [  9 -12  15]
 [ 15 -20  25]]

Add row/columns in the Numpy array

We added one more column at the 4th position using np.hstack

Python3




ini_array = np.array([[6, 8, 10],
                      [9, -12, 15],
                      [15, -20, 25]])
 
# Array to be added as column
column_to_be_added = np.array([1, 2, 3])
 
# Adding column to numpy array
result = np.hstack((ini_array, np.atleast_2d(column_to_be_added).T))
 
# printing result
print("\nresultant array\n", str(result))


Output:

resultant array
 [[  6   8  10   1]
 [  9 -12  15   2]
 [ 15 -20  25   3]]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads