Python Program to add two matrices


April 8, 2022, Learn eTutorial
1188

In this simple python program, we need to add two matrices. It's a beginner-level python program on matrix.

To understand this example, you should have knowledge of the following Python programming topics:

What is the matrix?

In this python program on matrix, we have to add two matrices. Matrix means arranging numbers or elements of the same data type in rows and columns. A matrix is also called an Array of arrays. The number of rows and columns in a matrix is the Order of that matrix. 

For example, let's take a matrix, matrix A [2 3 4] then the matrix order is Rows * Columns, which means 1*3. Now we have to find the sum of two matrices of order 2*3. In matrix addiction, we have to add each element in all Rows and Columns.

How matrices added in python

Let us take an example of Matrix A and matrix B; now we have to add each element in Matrix A to each element in Matrix B. that is A[i][j] + B[i][j]. And print the result matrix C. 

In this python program, we have to find the sum of two matrices of order m*n, and for that, we have to initialize the sum matrix with elements as zero. For that implementation, we use a nested for loop in python to get the sum of each element in every row and column of the two matrices. The first for loop is for the row and the second for the column traversing. Finally, we have to find the sum as "Sum[i][j] = A[i][j] + B[i][j]" and now print the sum matrix using another for loop.

ALGORITHM

STEP 1: In this python program, we have two matrices as A and B. Let's check the matrix order and store the matrix in a variable.

STEP 2: We have to initialize the sum matrix as the elements as zero.

STEP 3: Now, we have to use a nested loop to traverse the control through each element in every row and column.

STEP 4: Use the statement "sum[i][j] = A[i][j] + B[i][j]" to find the sum of each element in the matrix and add it to the sum matrix in python.

STEP 5: Display the output matrix using the for loop.

Python Source Code

                                          A =  [ [1, 1, 1],
     [1, 1, 1],    # first matrix of order 3*3
     [1, 1, 1]]


B =   [[1, 2, 3],
      [4, 5, 6],    # second matrix of order 3*3
      [7, 8, 9]]

sum = [[0, 0, 0],
      [0, 0, 0],    # initializing the sum matrix with elements zero
      [0, 0, 0]]

for i in range(len(A)):              # using the nested for loop to traverse through the matrix A each row and column
    for j in range(len(A[0])):
        sum[i][j] = A[i][j] + B[i][j]     # calculating each element sum of two matrix

# displaying the output matrix
for num in sum:
    print(num)
                                      

OUTPUT

[[2 3 4]
 [5 6 7]
 [8 9 10]]