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
- Subtract Lists in Python
- Average of Numbers in List
- Remove item from List in Python
- Remove the First Element from List
- Remove the Last Element from List
- Delete all Elements in List
- Check for Duplicates in List
- Find Duplicates in List in Python
- Remove Special Characters From list
- Remove Duplicates from List in Python
Python Programs for Searching
Python String Programs
- Convert ASCII to String
- Convert String to ASCII
- List of Alphabets Python
- Check Special Character
- Print Alphabets in Python
- Concatenate String and int
- Palindrome String in Python
- How to Swap case in Python
- Check Two Strings are equal
- Capitalize First Letter in Python
- Print Vowels in a String in Python
- Print Consonants in a String in Python
- Print Vowels and Consonants in a String
- Separate Vowels and Consonants in a String
- Find Vowels in String in String
- Count Vowels in a String in Python
- Find Consonants in String in Python
- Count Consonants in a String in Python
- Find Vowels and Consonants in a String
- Check if String Contains Vowels
- Check if String Starts with Vowel
- Remove Vowels from String in Python