Write a program in python to add two matrices.

Example:

In python, a matrix can be represented using nested list. For example m1 = [[1,2],[8,1]] is a list having each element itself a list. Each row in a matrix can be denoted by m1[i] and theelement in the ith row and jth column as m1[i][j].

So using a nested for loop we can easily add each element of the first matrix to the corresponding element of the second matrix.

Method 1: Matrix Addition Using Nested For Loop

Recommended:

Output

In the above program we have used len(m1) to find number of rows and len(m1[0]) to find the number of column in the metrix m1.

Method 2: Matrix Addition using List Comprehension

In this method instead of using nested for loop, we will use list comprehension to add matrices. I highly recommend you to read our list comprehension tutorial if you don’t know what it is?

Output

If you have any suggestions or doubts then comment below.

Leave a Reply

Close Menu