VOOZH about

URL: https://www.geeksforgeeks.org/python/adding-and-subtracting-matrices-in-python/

⇱ Adding and Subtracting Matrices in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Adding and Subtracting Matrices in Python

Last Updated : 22 Sep, 2025

In this article, we will learn how to add and subtract matrices in Python using both NumPy (fast and simple) and nested loops (manual approach).

For 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]] #Addition
A-B = [[-3,-3],[-3,-3]] #Subraction

Adding Matrices

NumPy provides the np.add() function, which adds two matrices element-wise.


Output
Matrix A:
 [[1 2]
 [3 4]]
Matrix B:
 [[4 5]
 [6 7]]
Result:
 [[ 5 7]
 [ 9 11]]

Explanation: np.add(A, B) adds corresponding elements of matrices A and B and result is a new matrix C with element-wise sums.

Subtracting Matrices

NumPy also provides np.subtract(), which subtracts one matrix from another element-wise.


Output
Matrix A:
 [[1 2]
 [3 4]]
Matrix B:
 [[4 5]
 [6 7]]
Result:
 [[-3 -3]
 [-3 -3]]

Explanation: np.subtract(A, B) subtracts each element of B from A and result is a matrix with the element-wise differences.

Adding and Subtracting Matrices using Nested Loops

This manual approach uses nested loops to perform both addition and subtraction of two matrices without using NumPy.


Output
Matrix 1:
[1, 2]
[3, 4]
Matrix 2:
[4, 5]
[6, 7]
Addition Result:
[5, 7]
[9, 11]
Subtraction Result:
[-3, -3]
[-3, -3]

Explanation: We iterate over rows (i) and columns (j) using nested loops. At each index [i][j], we calculate both:

  • add_result[i][j] = matrix1[i][j] + matrix2[i][j]
  • sub_result[i][j] = matrix1[i][j] - matrix2[i][j]
  • Finally, both results are printed row by row.
Comment