Python Program - Add Two Matrices

www.ig‮c.aeditfi‬om

Here's a Python program to add two matrices of the same size:

# define two matrices
matrix1 = [[1, 2, 3],
           [4, 5, 6],
           [7, 8, 9]]

matrix2 = [[10, 11, 12],
           [13, 14, 15],
           [16, 17, 18]]

# create an empty matrix to store the result
result = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]

# iterate through rows of matrices
for i in range(len(matrix1)):
    # iterate through columns of matrices
    for j in range(len(matrix1[0])):
        # add corresponding elements of matrices and store the sum in result matrix
        result[i][j] = matrix1[i][j] + matrix2[i][j]

# print the result
for r in result:
    print(r)

Output:

[11, 13, 15]
[17, 19, 21]
[23, 25, 27]

In this program, we have two matrices, matrix1 and matrix2, of the same size. We create an empty matrix result of the same size to store the result of adding matrix1 and matrix2.

We then use nested for loops to iterate through each element of the matrices and add the corresponding elements, storing the sum in result.

Finally, we print the resulting matrix.