Skip to content

Instantly share code, notes, and snippets.

@stevenrouk
Created August 25, 2019 22:50
Show Gist options
  • Select an option

  • Save stevenrouk/f1d7b5a6142d825324d95122a946f3ba to your computer and use it in GitHub Desktop.

Select an option

Save stevenrouk/f1d7b5a6142d825324d95122a946f3ba to your computer and use it in GitHub Desktop.
import numpy as np
def for_loop_matrix_multiplication3(A, B):
"""Third version of a for loop matrix multiplication.
In this version, we replace the NumPy arrays with lists
and figure out how to store the resulting dot product values
in the correct places for the new matrix."""
# We're going to leave these as NumPy arrays for now because we're
# still transposing B using the "B.T" functionality of np.array.
A = np.array(A)
B = np.array(B)
# Instead of a NumPy array, we're just going to use lists now!
new_matrix = []
for i, row in enumerate(A):
new_row = []
for j, col in enumerate(B.T):
dot_product = sum([x*y for (x, y) in zip(row, col)])
# Appending this value to the list is essentially storing
# a new column value for the same row in our new matrix.
# So the new_row list represents a row in the new matrix,
# and we add values to that row one by one as we multiply
# our row in A by each column in B.
new_row.append(dot_product)
# Now, we need to append the new_row to our new_matrix
# before moving on to the next row in A.
new_matrix.append(new_row)
return new_matrix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment