Matrix Addition in Python using Function

Matrix Addition in Python using Function | Here, we will discuss matrix addition in python using function. For adding any two matrices, both the matrices should be of the same dimension; we carry out the addition by adding corresponding elements together. Similar to the add operation, we can also implement other mathematical operations.

Matrix Addition in Python Using Function

In python we can define our own function, so by using this we can add two matrices. Here in the below code, we have defined a function called add() which takes two parameters m1 and m2.

# Python program to add two matrices using function

def add(m1, m2):
   new = []
   for i in range(0, len(m1)):
      new.append(m1[i] + m2[i])
   return new


# main
m1 = [[9, 8], [9, 0]]
m2 = [[8, 8], [6, 5]]
c = []
for i in range(0, len(m1)):
   c.append(add(m1[i], m2[i]))

print("Add Matrix:")
print(c)

Output:

Add Matrix:
[[17,16], [15,5]]

In the add() function, we initiate new to an empty array, then we append new to the addition of matrix 1 and matrix2. Then in the main function, we take two matrices and then call add() to add the matrices and store them in c. 

By adding matrix 1 [9,8] and [9,0] and matrix2 [8,8] and [6,5] we get the above output that is [17,16] [15,5]. 

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Python Program Examples with Output

Python Programs for Searching

Python String Programs

Leave a Comment

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