aks
aks

Reputation: 1

Error solving matrix product using nested for loops

I am trying to obtain matrix product using nested for loop but it throws an error..

import numpy as np
A = np.array([1,7,8],[2,7,9],[4,8,8]])
B = np.array([[3,5,6]])

for i in range(len(A)):
   for j in range(len(B[0])):
       for k in range(len(A)):
           C[i][j]+=A[i][k]*B[k][j]
print C

Upvotes: 0

Views: 227

Answers (3)

Joshua Cook
Joshua Cook

Reputation: 13435

Is there a reason why you are explicitly performing the multiplication yourself? This will not scale well. You should use

C = np.dot(B,A)

or

C= B.dot(A)

Note also that numpy is row major, thus the reversed order of the multiplication.

Upvotes: 0

philngo
philngo

Reputation: 931

Try this: (Note B is vertical)

A = np.array([[1,7,8],[2,7,9],[4,8,8]])
B = np.array([[3],[5],[6]])
C = np.zeros((3,1))

for i in range(len(A)):
    for j in range(len(B[0])):
        for k in range(len(A)):
            C[i][j] += A[i][k]*B[k][j]

But you also just use np.dot(A,B), which takes advantage of vectorization.

Upvotes: 1

Kerem
Kerem

Reputation: 2897

Your problem is with the indentation and undefined C. You're probably getting C is not defined error because you simply haven't done so. Define matrix C just like you did with your other matrices and be careful with your indentations, if you define it inside your loops, you can't print it outside either, it would still be undefined outside the scope of your loops.

Upvotes: 0

Related Questions