Python-Matrix Addition


This code defines a function mat_add that adds three matrices A, B, and C.

def mat_add(A,B,C):
    if(len(A)==len(B) and (len(B)==len(C)) and (len(A[0])==len(B[0])) and (len(B[0])==len(C[0]))):
        for i in range(len(A)):
            for j in range(len(A[0])):
                A[i][j]=A[i][j]+B[i][j]+C[i][j]
        return A 
    else:
        return -1

A=[[1,2,3],[1,2,3],[2,4,6]]
B=[[1,2,3],[1,2,3],[2,4,6]]
C=[[1,2,3],[1,2,3],[2,4,7]]
x=mat_add(A,B,C)
print(x)

Here’s a line-by-line explanation of the function :

  1. def mat_add(A, B, C):
    This line defines a function named mat_add that takes three inputs: matrices A, B, and C.
  2. if(len(A) == len(B) and len(B) == len(C) and len(A[0]) == len(B[0]) and len(B[0]) == len(C[0])):
    The function checks whether the three matrices have the same number of rows and the same number of columns. If they do, the function will proceed to add them together.
  3. for i in range(len(A)):
    If the matrices have the same dimensions, this line starts a loop that goes through each row of the matrices.
  4. for j in range(len(A[0])):
    Inside the first loop, this line starts another loop that goes through each column within the current row.
  5. A[i][j] = A[i][j] + B[i][j] + C[i][j]:
    For each element in the matrix, this line adds the corresponding elements from matrices B and C to the element in matrix A. This updates the value of A[i][j] with the sum of the three matrices’ elements at that position.
  6. return A:
    After all the elements have been added, the function returns the modified matrix A, which now contains the sum of the original matrices.
  7. else:
    If the dimensions of the matrices do not match, the function moves to this line.
  8. return -1:
    If the matrices don’t have the same dimensions, the function returns -1 to indicate an error.

Example :

Let’s define three matrices, A, B, and C:

Matrix A is [[1, 2, 3], [1, 2, 3], [2, 4, 6]]

Matrix B is [[1, 2, 3], [1, 2, 3], [2, 4, 6]]

Matrix C is [[1, 2, 3], [1, 2, 3], [2, 4, 7]]

When the function mat_add(A, B, C) is called, it first checks if the dimensions of all three matrices match. In this case, they do. The function then proceeds to add the corresponding elements from matrices B and C to each element in matrix A and returns the resulting matrix.

The resulting matrix after adding these matrices together would be:

[[3, 6, 9], [3, 6, 9], [6, 12, 19]]

For instance, the element in the third row and third column of the resulting matrix is calculated as 6 + 6 + 7 = 19.