Skip to content

Instantly share code, notes, and snippets.

@stevenrouk
Created August 25, 2019 22:34
Show Gist options
  • Save stevenrouk/758b6238e0fd120bffb761b97cd0623d to your computer and use it in GitHub Desktop.
Save stevenrouk/758b6238e0fd120bffb761b97cd0623d to your computer and use it in GitHub Desktop.
import numpy as np
def for_loop_matrix_multiplication2(A, B):
"""Second version of a for loop matrix multiplication.
In this version, we remove the np.dot() function."""
A = np.array(A)
B = np.array(B)
new_matrix = np.zeros((A.shape[0], B.shape[1]))
for i, row in enumerate(A):
for j, col in enumerate(B.T):
# The zip function matches up the arrays nicely so that
# values at the same index are paired up into a tuple.
# Then, we unpack those tuples one by one, multiply the values
# together, create a list with all those values, then sum the
# values in the list.
dot_product = sum([x*y for (x, y) in zip(row, col)])
new_matrix[i, j] = dot_product
return new_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment