Here you’ll get the program for python matrix operation. In python “list” construct is there instead of arrays. For implementing matrix we should always take facilitate of lists in python. Matrix will be delineated as nested lists.

Suppose if we would like to implement 2×3 matrix then python syntax can appear as if this.

Matrix=[[1,2,3],[4,5,6]] #This is 2×3 matrix

If we would like to implement 3×2 matrix then

Matrix=[[1,2],[3,4],[5,6]] #This is 3×2 matrix.

Python matrix operation

Below is the python program for addition of 2 matrices. Program is created and tested in python three.

Code

``````def print_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print("\t",matrix[i][j],end=" ")
print("\n")
def main():
m=int(input("enter rows"));
n=int(input("enter columns"));

#in python initilization is needed before indexing.
matrix1=[[0 for j in range(0,n)] for i in range(0,m)]   # matrix 1 initialization with 0s
matrix2=[[0 for j in range(0,n)] for i in range(0,m)]    #matrix 2 intialization with 0s
res_matrix=[[0 for j in range(0,n)] for i in range(0,m)] # matrix for storing result
print("enter first matrix elements")
for i in range(0,m):
for j in range(0,n):
matrix1[i][j]= int(input("enter an element"))
print("enter second matrix elements ")
for i in range(0,m):
for j in range(0,n):
matrix2[i][j]=int(input("enter an element"))

for i in range(0,m):
for j in range(0,n):
res_matrix[i][j]=matrix1[i][j]+matrix2[i][j]

#print input matrices
print(" matrix 1")
print_matrix(matrix1)
print(" matrix 2")
print_matrix(matrix2)

# printing resultant matrix
print_matrix(res_matrix)

main()``````

Output

``````enter rows2
enter columns2
enter first matrix elements
enter an element1
enter an element2
enter an element3
enter an element2
enter second matrix elements
enter an element1
enter an element2
enter an element3
enter an element4
matrix 1 1 2
matrix 2
3 2
1 2 3 4