Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save stevenrouk/5e248ba2a7a3002dd06add9c5fa7cb9a to your computer and use it in GitHub Desktop.
import numpy as np
def for_loop_matrix_multiplication(A, B):
# A and B might come in as lists. We'll figure out
# how to deal with this eventually, but for now let's
# convert them to NumPy arrays so that we can transpose
# matrix B. (This is so we can iterate through the columns
# of B, rather than the rows.)
A = np.array(A)
B = np.array(B)
# Our new matrix is going to have the same number
# of rows as A, and the same number of columns as B.
# Let's create a new NumPy array with that shape so we
# can store results as we compute them.
new_matrix = np.zeros((A.shape[0], B.shape[1]))
# Now, we'll take each row of A, dot product it with
# each col of B, and store the result in the right place
# in our new matrix.
for i, row in enumerate(A):
for j, col in enumerate(B.T):
dot_product = np.dot(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