Helmon Betancourth
Helmon Betancourth

Reputation: 1

Matrix Product in Python

I am trying to multiply two matrices together. I made a class for the matrices but I am having trouble with the implementing the mathematical algorithm part of the product. I know the # of columns in the first matrix should equal the rows in the second but this is giving me a different output. And more importantly the top row in M1 should dot prod with the first column of M2 to equal the first term in the result but it is not.

def Mult(self,Matrix):
    result=ClassMatrix()
    result.addRow(self.numberofRows)
    result.addColumn(Matrix.numberofColumns)
    for i in range(0,self.numberofRows):
       for j in range(0,Matrix.numberofColumns):
            result.content[i][j]=float(0.0)
    for i in range(0,self.numberofRows):
       for j in range(0,Matrix.numberofColumns):
              for k in range(0,self.numberofRows):
               result.content[i][j] += self.content[i][k] * Matrix.content[k][j]
   return result

for example multiplying a 3x2 and a 2x2 matrix is giving me a 2x2 matrix and the output is not the correct integer value. I want to do this without using numpy

Upvotes: 0

Views: 623

Answers (2)

user13732804
user13732804

Reputation:

You can use the following approach it will be much more intuitive and easier to maintain.

import numpy as np

def Mult(self,Matrix):
    result = ClassMatrix()

    # not sure about addRow and addColumn methods but 
    # if we can simply update content or pass it as a param to constructor
    # then next 2 statements will not be required
    result.addRow(self.numberofRows)
    result.addColumn(Matrix.numberofColumns)

    # using numpy dot product for matrix multiplication
    result.content = np.dot(self.content, Matrix.content)
    
    return result

Upvotes: 0

kosist
kosist

Reputation: 3057

I guess you could try like this:

def Mult(self,Matrix):
    result=ClassMatrix()
    result.addRow(self.numberofRows)
    result.addColumn(Matrix.numberofColumns)
    for i in range(0,self.numberofRows):
       for j in range(0,Matrix.numberofColumns):
           for k in range(0,Matrix.numberofRows):
               result.content[i][j] += self.content[i][k] * Matrix.content[k][j]
    return result

e.g. fix indentation, remove outer loop, and use in the inner loop number of rows and columns of matrix to multiply with. If you'd share all the code, it would be easier to test...

Upvotes: 1

Related Questions