Skip to content
Laviyx Learn

Try

Python Lab · Experiment 24

Addition of two square matrices

PythonWeek 5JNTUH R22 · CS206ES

Aim

To write a Python program that reads the size n and the values of two n × n matrices from the user, adds them, and prints the sum matrix.

Algorithm

  1. Read the size n. If n is not a positive number, print a message and stop.
  2. Read matrix A one row at a time. Split each line into n integers; if a line does not have exactly n numbers, ask for that row again.
  3. Read matrix B in the same way.
  4. Create the result matrix C. For every row i and column j, set C[i][j] = A[i][j] + B[i][j].
  5. Print A, B and C in rows and columns.

Program

Python
def read_matrix(n, name):
    print(f"Enter matrix {name} ({n} numbers per row):")
    matrix = []
    for i in range(n):
        row = [int(x) for x in input(f"Row {i + 1}: ").split()]
        while len(row) != n:
            print(f"Please enter exactly {n} numbers")
            row = [int(x) for x in input(f"Row {i + 1}: ").split()]
        matrix.append(row)
    return matrix


def add_matrices(a, b):
    n = len(a)
    result = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(a[i][j] + b[i][j])
        result.append(row)
    return result


def print_matrix(matrix):
    for row in matrix:
        for value in row:
            print(f"{value:5}", end="")
        print()


def main():
    n = int(input("Enter the size of the square matrices: "))
    if n <= 0:
        print("Size must be a positive number")
        return

    a = read_matrix(n, "A")
    b = read_matrix(n, "B")
    c = add_matrices(a, b)

    print("Matrix A:")
    print_matrix(a)
    print("Matrix B:")
    print_matrix(b)
    print("Sum A + B:")
    print_matrix(c)


main()

Output

Two 3 × 3 matrices

Output 1
Enter the size of the square matrices: 3
Enter matrix A (3 numbers per row):
Row 1: 1 2 3
Row 2: 4 5 6
Row 3: 7 8 9
Enter matrix B (3 numbers per row):
Row 1: 9 8 7
Row 2: 6 5 4
Row 3: 3 2 -1
Matrix A:
    1    2    3
    4    5    6
    7    8    9
Matrix B:
    9    8    7
    6    5    4
    3    2   -1
Sum A + B:
   10   10   10
   10   10   10
   10   10    8

A row with the wrong number of values is asked again

Output 2
Enter the size of the square matrices: 2
Enter matrix A (2 numbers per row):
Row 1: 10 20
Row 2: 30
Please enter exactly 2 numbers
Row 2: 30 40
Enter matrix B (2 numbers per row):
Row 1: 1 2
Row 2: 3 4
Matrix A:
   10   20
   30   40
Matrix B:
    1    2
    3    4
Sum A + B:
   11   22
   33   44

Recorded by running this exact program. Typed input appears after each prompt.

How it works

Each row is typed on one line with spaces between the numbers. input().split() breaks the line into a list of strings, and [int(x) for x in ...] turns each string into an integer.

Two matrices can be added only when they have the same number of rows and columns. This program reads square matrices of the same size n, so the sizes always match.

In real projects the numpy library does this in one step: numpy.array(a) + numpy.array(b) adds two arrays element by element. The lab asks for the loop version so that you see how the addition works.

Common mistakes

  • Writing a + b for two lists of lists. For Python lists, + joins the lists (A's rows followed by B's rows); it does not add the numbers. Add element by element with loops.

  • Creating the result as [[0] * n] * n and then filling it. All rows are the same list, so every row ends up equal to the last one. Build each row separately, as this program does.

  • Forgetting to convert the input to int. Then '1' + '9' joins the strings and gives '19' instead of 10.

  • Using range(n + 1) or starting from 1, which goes past the last row and raises IndexError.

Viva questions

Try to answer each one aloud before you open it.

  • When can two matrices be added?

    Only when they have the same order, that is, the same number of rows and the same number of columns. The sum has that same order.

  • What does [1, 2] + [3, 4] give in Python?

    [1, 2, 3, 4]. The + operator joins lists; it does not add them element by element.

  • How many additions are done to add two n × n matrices?

    One for each element, so n × n additions. For two 3 × 3 matrices that is 9 additions.

  • What does input().split() return?

    A list of the words in the line, split at spaces. For the line 1 2 3 it returns ['1', '2', '3'], which are still strings.

  • How would you add two matrices using numpy?

    Convert them to arrays and use +: numpy.array(a) + numpy.array(b). For numpy arrays + adds element by element.

Learn the concepts

All Python Programming Lab experiments →