0
votes

Well, I want to implement a multiplication matrix by a vector in Python without NumPy. So given a matrix for example (2x2) in this format:

A = [ [2, 1],
      [5, 7] ]

And given a vector for example (2x1) in this format:

b = [ [11],
      [13] ]

And I want to get this vector (2x1):

с = [ [35],
      [146] ]

What I tried:

def myzeros(n): # create zero vector
    res = []
    for i in range(n):
        res.append([0])

    return res

def mydot(A, B):
    res = myzeros(len(B)) # create zero vector of size B
    for i in range(len(A)):
        res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) )
    return res

And corresponding error:

res.append( sum(A[i][j]*B[j] for j in range(len(A[0]))) ) 
  TypeError: unsupported operand type(s) for +: 'int' and 'list'

Where's the mistake?

1
you are calling sum on a generator that is returning list objects. That is because A[i][j]*B[j] evaluates to a list, I believe you meant A[i][j]*B[j][i] - juanpa.arrivillaga

1 Answers

1
votes

Let's define vectors as Python lists, and matrices as lists of lists.

b = [11, 13]
A = [ [2, 1],
      [5, 7] ]

Then, you could use

def mydot(v1, v2):
     return sum([x*y for x,y in zip(v1, v2)])

def matmulvec(M, v):
    return [mydot(r,v) for r in M]

to get

matmulvec(A, b)
    [35, 146]