The Wayback Machine - https://web.archive.org/web/20240910073104/https://www.geeksforgeeks.org/python-program-add-two-matrices/
Open In App

Python Program to Add Two Matrices

Last Updated : 06 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given two matrices X and Y, the task is to compute the sum of two matrices and then print it in Python. 

Examples: 

Input :
X= [[1,2,3],
[4 ,5,6],
[7 ,8,9]]

Y = [[9,8,7],
[6,5,4],
[3,2,1]]

Output :
result= [[10,10,10],
[10,10,10],
[10,10,10]]

Add Two Matrices Using for loop

Here we will use for loop with two matrices for adding the elements

Python
# Program to add two matrices using nested loop

X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]

Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]


result = [[0,0,0],
        [0,0,0],
        [0,0,0]]

# iterate through rows
for i in range(len(X)):   
# iterate through columns
    for j in range(len(X[0])):
        result[i][j] = X[i][j] + Y[i][j]

for r in result:
    print(r)

Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Time Complexity: O(len(X) * len(X[0])), as we are using nested loop for traversing the matrix.
Auxiliary Space: O(len(X) * len(X[0])), as we are using a result matrix which is extra space.

Add Two Matrices Using List comprehension

In this program we have used nested for loops to iterate through each row and each column. At each point we add the corresponding elements in the two matrices and store it in the result.

Using nested list comprehension : In Python, we can implement a matrix as nested list (list inside a list). We can treat each element as a row of the matrix. 

Below is the implementation:

Python
# Program to add two matrices
# using list comprehension
 
X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]
 
Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]

result = [[X[i][j] + Y[i][j]  for j in range
(len(X[0]))] for i in range(len(X))]
 
for r in result:
    print(r)

Output
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Time Complexity: O(len(X) * len(X[0])), as we are using nested loop for traversing the matrix.
Auxiliary Space: O(len(X) * len(X[0])), as we are using a result matrix which is extra space.

Add Two Matrices Using zip() function

The output of this program is the same as above. We have used nested list comprehension to iterate through each element in the matrix. List comprehension allows us to write concise codes and we must try to use them frequently in Python. They are very helpful.

Below is the implementation:

Python
# Program to add two matrices
# using zip()
 
X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]
 
Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]

result = [map(sum, zip(*t)) for t in zip(X, Y)]
 
print(result)

Output
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]

Time Complexity: O(len(X) * len(X[0])), as we are using zip function.
Auxiliary Space: O(len(X) * len(X[0])), as we are using extra space.

Explanation:- The zip function accepts iterator i of each element(list) of matrix, mapping them, adding them using sum(), and storing them in the map form.

Add Two Matrices Using Numpy

The numpy library has a built-in overload of the operator +, that allows one to perform the addition of matrices.

Below is the implementation:

Python
# Program to add two matrices
# using numpy

import numpy as np
 
X = [[1,2,3],
    [4 ,5,6],
    [7 ,8,9]]
 
Y = [[9,8,7],
    [6,5,4],
    [3,2,1]]

result = np.array(X) + np.array(Y)

print(result)

Output:

[[10 10 10]
[10 10 10]
[10 10 10]]

Time Complexity: O(len(X) * len(X[0]))
Auxiliary Space: O(len(X) * len(X[0]))

Add Two Matrices Using SymPy

To add matrices using a library, you can use the Matrix class provided in the SymPy library.

Here’s an example of how to use it:

Python
from sympy import Matrix

X = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

Y = [[9, 8, 7],
     [6, 5, 4],
     [3, 2, 1]]

# Create Matrix objects from the lists
matrix_x = Matrix(X)
matrix_y = Matrix(Y)

# Add the matrices
result = matrix_x + matrix_y

# Print the result
print(result)

Output:

Matrix([
[10, 10, 10],
[10, 10, 10],
[10, 10, 10]])


Previous Article
Next Article

Similar Reads

Python | Convert LaTeX Matrices into SymPy Matrices using Python
A matrix is a rectangular two-dimensional array of data like numbers, characters, symbols, etc. which we can store in row and column format. We can perform operations on elements by using an index (i,j) where 'i' and 'j' stand for an index of row and column respectively. In the Python programming language, we can represent them in many formats like
5 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Python Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Examples: Input : mat1[][] = {{1, 2}, {3, 4}} mat2[][] = {{1, 1}, {1, 1}} Output : {{3, 3}, {7, 7}} Input : mat1[][] = {{2, 4}, {3, 4}} mat2[][] = {{1, 2}, {1, 3}} Output : {{6, 16}, {7, 18}}Recommended: Please solve it on "PRACTICE" first, before moving on
3 min read
Python Program for Kronecker Product of two matrices
Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22
3 min read
Python program to multiply two matrices
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output : [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111, 21]Using Simple Nested Loops: In this program we have to use nested for loops to iterat
4 min read
Program to concatenate two given Matrices of same size
Given two matrices A and B of size M x N, the task is to concatenate them into one matrix.Concatenation of matrix: The process of appending elements of every row of the matrix one after the other is known as the Concatenation of matrix. Examples: Input: A[][] = {{1, 2}, {3, 4}}, B[][] = {{5, 6}, {7, 8}} Output: 1 2 5 6 3 4 7 8 Explanation: Elements
6 min read
Program for addition of two matrices
Given two N x M matrices. Find a N x M matrix as the sum of given matrices each value at the sum of values of corresponding elements of the given two matrices. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: Below is the idea to solve the problem. Iterate over every cell of matrix (i, j), add the corres
7 min read
Program to check if two given matrices are identical
The below program checks if two square matrices of size 4*4 are identical or not. For any two matrices to be equal, a number of rows and columns in both the matrix should be equal and the corresponding elements should also be equal. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Implementation: C/C++ Code // C++
6 min read
Javascript Program for Kronecker Product of two matrices
Given a [Tex]{m} imes{n} [/Tex]matrix A and a [Tex]{p} imes{q} [/Tex]matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is an [Tex]{(mp)} imes{(nq)} [/Tex]matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22
3 min read
Program to multiply two matrices
Given two matrices, the task is to multiply them. Matrices can either be square or rectangular: Examples:  (Square Matrix Multiplication) Input: mat1[m][n] = { {1, 1}, {2, 2} }mat2[n][p] = { {1, 1}, {2, 2} }Output: result[m][p] = { {3, 3}, {6, 6} } (Rectangular Matrix Multiplication) Input: mat1[3][2] = { {1, 1}, {2, 2}, {3, 3} }mat2[2][3] = { {1,
14 min read
Javascript Program to multiply two matrices
Given two matrices, the task to multiply them. Matrices can either be square or rectangular. Example:  Input : mat1[][] = {{2, 4}, {1, 4}} mat2[][] = {{1, 4}, {1, 3}} Output : {{6, 16}, {7, 18}} Multiplication of Square Matrices : The below program multiplies two square matrices of size 4*4, we can change N for different dimensions. [GFGTABS] JavaS
3 min read
Multiplication of two Matrices in Single line using Numpy in Python
Matrix multiplication is an operation that takes two matrices as input and produces single matrix by multiplying rows of the first matrix to the column of the second matrix.In matrix multiplication make sure that the number of columns of the first matrix should be equal to the number of rows of the second matrix. Example: Multiplication of two matr
3 min read
Find the intersection of two Matrices
Given two matrix A[][] and B[][] of same order m*n. The task is to find the intersection of both matrix as C, where: Cij = Aij if Aij = BijC = "*", otherwise. Examples: Input : A[N][N] = {{2, 4, 6, 8}, {1, 3, 5, 7}, {8, 6, 4, 2}, {7, 5, 3, 1}}; B[N][N] = {{0, 4, 3, 8}, {1, 3, 5, 7}, {8, 3, 6, 2}, {4, 5, 3, 4}}; Output : * 4 * 8 1 3 5 7 8 * * 2 * 5
6 min read
Check if it is possible to make two matrices strictly increasing by swapping corresponding values only
Given two n * m matrices A[][] and B[][], the task is to make both the matrices strictly increasing (both rows and columns) only by swapping two elements in different matrices if they are located in the corresponding position i.e. A[i][j] can only be swapped with B[i][j]. If possible then print Yes otherwise, No.Examples: Input: A[][] = {{2, 10}, B
7 min read
Kronecker Product of two matrices
Given an m*n matrix A and a p*q matrix B, their Kronecker product C = A tensor B, also called their matrix direct product, is a (m*p) * (n*q) matrix. A tensor B = |a11B a12B| |a21B a22B| = |a11b11 a11b12 a12b11 a12b12| |a11b21 a11b22 a12b21 a12b22| |a11b31 a11b32 a12b31 a12b32| |a21b11 a21b12 a22b11 a22b12| |a21b21 a21b22 a22b21 a22b22| |a21b31 a21
10 min read
Count pairs from two sorted matrices with given sum
Given two sorted matrices mat1 and mat2 of size n x n of distinct elements. Given a value x. The problem is to count all pairs from both matrices whose sum is equal to x. Note: The pair has an element from each matrix. Matrices are strictly sorted which means that matrices are sorted in a way such that all elements in a row are sorted in increasing
15+ min read
Program for subtraction of matrices
The below program subtracts of two square matrices of size 4*4, we can change N for a different dimension. Implementation: C/C++ Code // C++ program for subtraction of matrices #include <bits/stdc++.h> using namespace std; #define N 4 // This function subtracts B[][] from A[][], and stores // the result in C[][] void subtract(int A[][N], int
7 min read
Multiply matrices of complex numbers using NumPy in Python
In this article, we will discuss how to multiply two matrices containing complex numbers using NumPy but first, let's know what is a complex number. A Complex Number is any number that can be represented in the form of x+yj where x is the real part and y is the imaginary part. Multiplication of two complex numbers can be done using the below formul
2 min read
Adding and Subtracting Matrices in Python
In this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of the matrix In the above code, we have used np.add()
4 min read
Python program to add two binary numbers
Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digit
4 min read
Python program to add two Octal numbers
Given two octal numbers, the task is to write a Python program to compute their sum. Examples: Input: a = "123", b = "456" Output: 601 Input: a = "654", b = "321" Output: 1175Approach: To add two octal values in python we will first convert them into decimal values then add them and then finally again convert them to an octal value. To convert the
2 min read
Python Program To Add Two Numbers Represented By Linked Lists- Set 1
Given two numbers represented by two lists, write a function that returns the sum list. The sum list is a list representation of the addition of two input numbers. Example: Input: List1: 5->6->3 // represents number 563 List2: 8->4->2 // represents number 842 Output: Resultant list: 1->4->0->5 // represents number 1405 Explanation: 563 + 842 = 1405
4 min read
Python Program to add two hexadecimal numbers
Given two hexadecimal numbers, write a Python program to compute their sum. Examples: Input: a = "01B", b = "378" Output: 393 Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 0 0 + 3 + 0 (carry) = 3, hence addition bit = 3, carry = 0 01B + 378 = 393 Input:
6 min read
Operations on Sparse Matrices
Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matrices, one by multiplying the two matrices and one o
15+ min read
Queries on number of Binary sub-matrices of Given size
Given a Binary Matrix of size N X M, the task is to answer Q queries of the following type; Query(a, b): Find the number of sub matrices of size a X a with each of its element consisting of the Binary Number b. We basically need to find submatrices of given sizes with all 1s or all 0s. Examples: Input : N = 5, M = 4 m[][] = { { 0, 0, 1, 1 }, { 0, 0
12 min read
Count of matrices (of different orders) with given number of elements
Given a number N denotes the total number of elements in a matrix, the task is to print all possible order of matrix. An order is a pair (m, n) of integers where m is number of rows and n is number of columns. For example, if the number of elements is 8 then all possible orders are: (1, 8), (2, 4), (4, 2), (8, 1).Examples: Input: N = 8 Output: (1,
5 min read
XOR of XORs of all sub-matrices
Given a 'N*N' matrix, the task is to find the XOR of XORs of all possible sub-matrices.Examples: Input :arr = {{3, 1}, {1, 3}} Output : 0 Explanation: All the elements lie in 4 submatrices each. 4 being even, there total contribution towards final answer becomes 0. Thus, ans = 0. Input : arr = {{6, 7, 13}, {8, 3, 4}, {9, 7, 6}}; Output : 4 A Simple
6 min read
Check if matrix can be converted to another matrix by transposing square sub-matrices
Given two N X M matrices of integers. In an operation, we can transpose any square sub-matrix in matrix1. The task is to check if matrix1 can be converted to matrix2 with the given operation.Examples: Input: matrix1[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}}, matrix2[][] = { {1, 4, 7}, {2, 5, 6}, {3, 8, 9}} Output: Yes Transpose the whole matrix and
10 min read
Calculate inner, outer, and cross products of matrices and vectors using NumPy
Let's discuss how to find the inner, outer, and cross products of matrices and vectors using NumPy in Python. Inner Product of Vectors and Matrices To find the inner product of the vectors and matrices, we can use the inner() method of NumPy.Syntax: numpy.inner(arr1, arr2) Code : C/C++ Code # Python Program illustrating # numpy.inner() method impor
2 min read
Count number of square sub matrices of given matrix whose sum of all cells is equal to S | Set 2
Given a matrix, arr[][] of dimensions M*N, and an integer S, the task is to print the count of the number of subsquares of the matrix, whose sum is equal to S. Examples: Input: M = 4, N = 5, S = 10, arr[][]={{2, 4, 3, 2, 10}, {3, 1, 1, 1, 5}, {1, 1, 2, 1, 4}, {2, 1, 1, 1, 3}} Output: 3 Explanation: Sub-squares {10}, {{2, 4}, {3, 1}} and {{1, 1, 1},
12 min read