w3resource

Numpy - Calculate Matrix product of two large arrays using For loops and Optimization


NumPy: Performance Optimization Exercise-19 with Solution


Write a function to calculate the matrix product of two large 2D NumPy arrays using nested for loops. Optimize it using NumPy's matmul() function.

Sample Solution:

Python Code:

import numpy as np

# Generate two large 2D NumPy arrays with random integers
array1 = np.random.randint(1, 100, size=(500, 500))
array2 = np.random.randint(1, 100, size=(500, 500))

# Function to calculate the matrix product using nested for loops
def matrix_product_with_loops(A, B):
    result = np.zeros((A.shape[0], B.shape[1]))
    for i in range(A.shape[0]):
        for j in range(B.shape[1]):
            for k in range(A.shape[1]):
                result[i, j] += A[i, k] * B[k, j]
    return result

# Calculate the matrix product using the nested for loops method
product_with_loops = matrix_product_with_loops(array1, array2)

# Calculate the matrix product using NumPy's matmul() function
product_with_numpy = np.matmul(array1, array2)

# Display first 5x5 section of the result to verify
print("Matrix product using for loops (first 5x5 elements):")
print(product_with_loops[:5, :5])

print("Matrix product using NumPy (first 5x5 elements):")
print(product_with_numpy[:5, :5])

Output:

Matrix product using for loops (first 5x5 elements):
[[1272510. 1280577. 1151828. 1232191. 1328246.]
 [1282428. 1265964. 1181278. 1254038. 1291497.]
 [1193518. 1248841. 1188901. 1201621. 1287151.]
 [1256727. 1254756. 1196737. 1222706. 1348403.]
 [1265526. 1301441. 1208882. 1258619. 1372655.]]
Matrix product using NumPy (first 5x5 elements):
[[1272510 1280577 1151828 1232191 1328246]
 [1282428 1265964 1181278 1254038 1291497]
 [1193518 1248841 1188901 1201621 1287151]
 [1256727 1254756 1196737 1222706 1348403]
 [1265526 1301441 1208882 1258619 1372655]]

Explanation:

  • Importing numpy: We first import the numpy library for array manipulations.
  • Generating large arrays: Two large 2D NumPy arrays with random integers are generated.
  • Defining the function: A function matrix_product_with_loops is defined to calculate the matrix product using nested for loops.
  • Calculating with loops: The matrix product is calculated using the nested for loops method.
  • Calculating with numpy: The matrix product is calculated using NumPy's built-in matmul() function.
  • Displaying results: The first 5x5 section of the matrix product from both methods is printed out to verify correctness.

Python-Numpy Code Editor: