Python Matrix Addition

Here you will get program for python matrix addition. In python “list” concept is there rather than arrays.  For implementing matrix we should take help of lists in python. Matrix can be represented as nested lists.

Suppose if we want to implement 2×3 matrix then python syntax will look like this.

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

If we want to implement 3×2 matrix then

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

Python Matrix Addition

Below is python program for addition of two matrices. Program is made and tested in python 3.

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("resultant matrix after adding")
	print_matrix(res_matrix)
	
main()

Output

Python Matrix Addition

Leave a Comment

Your email address will not be published. Required fields are marked *