I am working with Matrix multiplication but have problem

index 1 is out of bounds for axis 0 with size 1

its working perfectly with sq matrix multiplication but having problem with rectangular matrix kindly find me the mistake

import numpy as np
A=np.array([[12,7,3],
    [4 ,5,6],
   [7 ,8,9]]) 
B=np.array([[1],[1],[1]])
r1,c1=A.shape
r2,c2=B.shape
C=np.array([[0 for j in range(c2)] for i in range(r1)])
if c1==r2:
    for k in range(r1):
        for i in range(c2+1):
            for j in range(c1):
                C[i][j]+=A[k][j]*B[j][i]
    print("Matrix After Multiplication \n\n",C)
else:
    print('Multiplication is not possible')

Upvotes: 0

Views: 55

Answers (2)

Jack Moody
Jack Moody

Reputation: 1771

I am not sure if there is a reason why you are not using the built-in np.dot() function, but if you need to explicitly make a for loop to do your matrix multiplication, you can replace your conditional statement with the following:

if c1==r2:
    for col in range(c2):
        for row in range(r1):
            for i in range(r1):
                C[row][col] += A[row][i]*B[i][col]
    print("Matrix After Multiplication \n\n",C)
else:
    print('Multiplication is not possible')

Your resulting matrix will be of size r1 by c2.

However, if you are able to use np.dot(), I would recommend you follow pyano's suggestion.

C = np.dot(A, B)

Either way will yield

C = [[22]
     [15]
     [24]]

Upvotes: 0

pyano
pyano

Reputation: 1978

I think

for i in range(c2+1):

runs out of the range, since

r2,c2=B.shape

so (c2+1) is too large.

But

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

C = A@B
C

or

C = np.dot(A,B)
C

is MUCH more efficient

Upvotes: 2

Related Questions