How to Find the Sum of a Matrix in Python

Contents
In this article, you will learn how to find the sum of a matrix in Python.
Find the Sum of a Matrix
Use the NumPy library
There is another way to find the sum of a matrix in Python, which uses the NumPy library. Here’s an example code:
import numpy as np
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# use the sum() method of the NumPy array to find the sum
sum = matrix.sum()
# print the sum
print("The sum of the matrix is:", sum)
This prints out the sum of all the elements in the matrix. The NumPy library provides many other useful functions for working with arrays, so it can be a powerful tool for numerical computation in Python.
Use nested for loops
To find the sum of a matrix in Python, you can use nested for loops to iterate over each element in the matrix and add them up. Here’s an example code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# initialize the sum to 0
sum = 0
# iterate over each row of the matrix
for i in range(len(matrix)):
# iterate over each column of the matrix
for j in range(len(matrix[i])):
# add the current element to the sum
sum += matrix[i][j]
# print the sum
print("The sum of the matrix is:", sum)
In this example, we have a 3×3 matrix and we use nested for loops to iterate over each element and add them up. The sum is stored in a variable sum and printed at the end of the code. You can replace the matrix values with your own matrix and the code should work as long as the matrix is a valid 2D list.
Use the sum() function
There is another way to find the sum of a matrix in Python, which uses the built-in sum() function and list comprehension. Here’s an example code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# use list comprehension to flatten the matrix into a 1D list
flat_list = [num for row in matrix for num in row]
# use the sum() function to find the sum of the flattened list
sum = sum(flat_list)
# print the sum
print("The sum of the matrix is:", sum)
This prints out the sum of all the elements in the matrix. You can replace the matrix variable with your own 2D list to find the sum of your own matrix.