Multiply matrix by list in Python

Question:

I am looking for a way to achieve the following in Python and can’t figure out how to do it:

a=[[0,1],[1,0],[1,1]]
b=[1,0,5]

c=hocuspocus(a,b)

--> c=[[0,1],[0,0],[5,5]]

So basically I would like to multiply the different matrix rows in a with the list b.

Thanks a lot in advance!

Asked By: Bart

||

Answers:

hocuspocus = lambda a,b: [[r*q for r in p] for p, q in zip(a,b)]
Answered By: Lie Ryan

Use Numpy, it has a function for cross multiplying, and other useful tools for matricies.

import * from numpy as np

a=[[0,1],[1,0],[1,1]]
b=[1,0,5]

prod = a * b
Answered By: Rob Wagner

Python lists don’t support that behaviour directly, but Numpy arrays do matrix multiplication (and various other matrix operations that you might want) directly:

>>> a
array([[0, 1, 1],
       [1, 0, 1]])
>>> b
array([1, 0, 5])
>>> a * b
array([[0, 0, 5],
       [1, 0, 5]])
Answered By: lvc
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.