Search code examples
pythonvectormultiplication

How can I multiply a vector with a matrix without numpy in Python


I'm trying to multiply a matrix with a vector but I can't find a way to make a vector without using NumPy I need to find a way to create a vector without numpy so I can multiply it with a matrix

I tried an answer I have found here but it doesn't seem to work when I try to use it.It doesn't do anything when I run it no errors no response nothing I just run it and nothing happens

Here is the code that I found from an answer here

def multiply(v, G):
result = []
for i in range(len(G[0])): #this loops through columns of the matrix
    total = 0
    for j in range(len(v)): #this loops through vector coordinates & rows of matrix
        total += v[j] * G[j][i]
    result.append(total)
return result

All this is coded in jupyter notebook


Solution

  • class noNumpy:
        def multiply(self,v,G):
            rMatrix = len(G[0]) #This gives us the number of elements inside a row of matrix.
            rVector = len(v) #This gives us the number of elements in vector
            nMatrix = len(G) #This gives us the number of rows of the matrix.
            totalList = []
    
            for i in (range(rVector)):
                for j in range(nMatrix):
                    for k in range(rMatrix):
                        totalList.append(v[i]*G[j][k])
    
            print(totalList)
    
    Matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
    vector = [1,2,3]
    n1 = noNumpy()
    n1.multiply(vector,Matrix)
    

    This is the sample code that is not using NumPy. However, note that Python itself is a slow language plus using three loops is also not feasible but for small lists I suppose it must be fine.

    I would appreciate any feedbacks and any better of doing this as well.