Home » Python Tutorial » How to Create a Matrix in Python?

# How to Create a Matrix in Python?

A matrix in python is a two-dimensional list. The matrix is made of rows and columns. We can add n number of rows and columns in the matrix. Matrix will be any type of number like integer, float, complex numbers. Also, we can make operations on the matrix. We can add, subtract, multiply and divide two matrices. Moreover, there are many operations we can perform on the matrix. Let’s understand this with examples.

## How to create a matrix in python?

There are two ways to implement a matrix in python.

### 1. Using a list to implement matrix.

In this, we create and operate the matrix manually. We need to declare functions for performing various operations on it.

#### Example

``````r = int(input("Enter number of rows:"))
c = int(input("Enter number of columns:"))

matrix = []

for i in range(r):
row = []
for j in range(c):
row.append(int(input("Enter element of [{}][{}]:".format(i,j))))
matrix.append(row)

print("Entered matrix is")

for i in range (r):
for j in range(c):
print(matrix[i][j], end=" ")
print("")``````

Output

``````Enter number of rows:3
Enter number of columns:3
Enter element of :1
Enter element of :2
Enter element of :3
Enter element of :4
Enter element of :5
Enter element of :6
Enter element of :7
Enter element of :8
Enter element of :9
Entered matrix is
1 2 3
4 5 6
7 8 9``````

### 2. Using NumPy library to implement matrix.

NumPy is a library in python. It is used to manage multidimensional arrays and matrices. To perform operations on it, NumPy provides a wide scale of inbuilt functions which will give appropriate output.

#### Example

``````import numpy as np

r = int(input("Enter number of rows:"))
c = int(input("Enter number of columns:"))

print("Enter data in single line separated by spaces")

data = list(map(int, input().split()))

matrix = np.array(data).reshape(r,c)

print(matrix)``````

Output

``````Enter number of rows:3
Enter number of columns:3
Enter data in single line separated by spaces
1 2 3 4 5 6 7 8 9
[[1 2 3]
[4 5 6]
[7 8 9]]``````

## Operations on matrix in python examples

We can perform many operations on a matrix in python. In this, we will perform add, subtract, multiply and divide operations into two matrices. Also, we will see how to perform transpose operations on the matrix. Let’s understand with an example.

### 1. Using list, create two matrices, perform addition and subtract operation.

Use NumPy library to use inbuilt functions. Create two matrices use add() and subtract() to add and subtract matrices.

#### Example

``````import numpy as np

m1 = [[1,2],[3,4]]
m2 = [[5,6],[7,8]]

m1 = np.array(m1).reshape(2,2)
m2 = np.array(m2).reshape(2,2)

print("1st matrix is :\n",m1)
print("2nd matrix is :\n",m2)

'''add = m1 + m2'''   #This is the simplest way to add two matrices
print("Addition of two matrices is :")

'''sub = m1 - m2''' #Simplest way to subtract two matrices
sub = np.subtract(m1,m2) # Subtraction of two matrices using subtract function.
print("Subtraction of two matrices is :")
print(sub)``````

Output

``````1st matrix is :
[[1 2]
[3 4]]
2nd matrix is :
[[5 6]
[7 8]]
Addition of two matrices is :
[[ 6  8]
[10 12]]
Subtraction of two matrices is :
[[-4 -4]
[-4 -4]]``````

### 2. Perform matrix multiplication and division in python.

Matrix multiplication in python using user input is very simple. Accept two matrices from the user and use dot() to perform multiplication of two matrices. The same goes with the division. There are many functions to divide two matrices. We used a divide function to divide them.

#### Example

``````import numpy as np

print("Enter values for 1st matrix")
r = int(input("Enter number of rows:"))
c = int(input("Enter number of columns:"))
print("Enter data in single line separated by spaces")
data = list(map(int, input().split()))
m1 = np.array(data).reshape(r,c)

print("Enter values for 2nd matrix")
r = int(input("Enter number of rows:"))
c = int(input("Enter number of columns:"))
print("Enter data in single line separated by spaces")
data = list(map(int, input().split()))
m2 = np.array(data).reshape(r,c)

print("1st matrix is :\n",m1)
print("2nd matrix is :\n",m2)

mul = m1.dot(m2) #Multiplication of two matrices using dot function
print("Multiplication of two matrices is :")
print(mul)

div = np.divide(m1,m2) #division using divide function
print("Division of two matrices is :")
print(div)``````

Output

``````Enter values for 1st matrix
Enter number of rows:3
Enter number of columns:3
Enter data in single line separated by spaces
9 3 1 6 7 3 5 7 2
Enter values for 2nd matrix
Enter number of rows:3
Enter number of columns:3
Enter data in single line separated by spaces
6 1 4 6 8 9 3 2 5
1st matrix is :
[[9 3 1]
[6 7 3]
[5 7 2]]
2nd matrix is :
[[6 1 4]
[6 8 9]
[3 2 5]]
Multiplication of two matrices is :
[[ 75  35  68]
[ 87  68 102]
[ 78  65  93]]
Division of two matrices is :
[[1.5        3.         0.25      ]
[1.         0.875      0.33333333]
[1.66666667 3.5        0.4       ]]``````

## Transpose of a matrix in python

Transpose of the matrix means changing the positions of row and column. The row becomes a column, and the column becomes a row.

#### Example

``````import numpy as np

print("Enter values for 1st matrix")
r = int(input("Enter number of rows:"))
c = int(input("Enter number of columns:"))
print("Enter data in single line separated by spaces")
data = list(map(int, input().split()))
m1 = np.array(data).reshape(r,c)

print("1st matrix is :\n",m1)

trans = m1.transpose()
print("Transpose of given matrix is :")
print(trans)``````

Output

``````Enter values for 1st matrix
Enter number of rows:3
Enter number of columns:3
Enter data in single line separated by spaces
1 2 3 4 5 6 7 8 9
1st matrix is :
[[1 2 3]
[4 5 6]
[7 8 9]]
Transpose of given matrix is :
[[1 4 7]
[2 5 8]
[3 6 9]]``````

## FAQ’s

How to print a matrix in python?

To print the matrix use a nested loop. An example is given below
for i in range (r):
for j in range(c):
print(matrix[i][j], end=” “)
print(“”)

How to take matrix input in python?

To take input from the user we need one list and append sublist in the main list. The example is given below
matrix = []
for i in range(r):
row = []
for j in range(c):
row.append(int(input(“Enter element of [{}][{}]:”.format(i,j))))
matrix.append(row)

Shares