BestDravenHildesheim
BestDravenHildesheim

Reputation: 37

Numpy.matmul sees array as integer

I have been trying to create a class for matrixes and this is what i have already:


import numpy as np
import random

class matrix(): 
    def __init__(self, rows, cols): 

        self.rows = rows
        self.cols = cols
        self.matrix = np.array([[0 for x in range(self.cols)] for y in range(self.rows)])


    def multiply(self, a): 
        self.matrix = np.matmul(self.matrix, a)

    def randomize(self): 
        for j in range(self.rows): 
            for i in range(self.cols):

                self.matrix[j][i] = random.randint(1,10)





m = matrix(4,3)
a = matrix(3, 3)
m.randomize()
a.randomize()

m.multiply(a)


What i expect this to do is to multiply m with a, in a sort of matrix fashion. i have a function which gives each value a nr between 0 and 10.

But i get this error message:

ValueError: matmul: Input operand 1 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)

Im sure its just something small i am overlooking but if not and its a bigger issue, please dont hesitate to ask questions. Thanks in advance

Upvotes: 0

Views: 438

Answers (1)

aminrd
aminrd

Reputation: 5050

Because you are trying to multiply a Numpy object, with an object of type of your matrix. In your multiply function, you should call np.matmul(self.matrix, a.matrix). Also, as Barmar suggested, you can increase the performance of your code by using self.matrix = np.zero((rows, cols)).


import numpy as np
import random

class matrix(): 
    def __init__(self, rows, cols): 

        self.rows = rows
        self.cols = cols
        self.matrix = np.zero((rows, cols))


    def multiply(self, a): 
        self.matrix = np.matmul(self.matrix, a.matrix)

Upvotes: 1

Related Questions