Matrix vector multiplication
Using 'reduce' and 'map', this code shows how a matrix vector multiplication can be reduced to a single loop.
There are numerous methods to compute the matrix vector operation. The above method is compact and elegant. However, it is not the fastest. For some reason, the following brute force approach is faster by about 10%:
def matmult2(m, v): " this is faster " nrows = len(m) ncols = len(m[0]) w = [None] * nrows for row in range(nrows): sum = 0 for col in range(ncols): sum += m[row][col]*v[col] w[row] = sum return w
This is somewhat counter-intuitive since there is an additional nested loop.
It shows that performance in Python is a tricky affair. Indeed, the test driver can be further accelerated by a factor 5 to 10 simply by initializing mat = [map(lambda x: float(i*n+x+1), range(n)) for i in range(m)] with floats for large n!
--Alex.
#!/usr/bin/env python
""" Matrix-vector multiplication """
def matmult(m, v):
nrows = len(m)
w = [None] * nrows
for row in range(nrows):
w[row] = reduce(lambda x,y: x+y, map(lambda x,y: x*y, m[row], v))
return w
#................................................
if __name__=='__main__':
m, n = 2, 3
vec = range(1, n+1)
mat = [map(lambda x: i*n+x+1, range(n)) for i in range(m)]
print 'vec=', vec
print 'mat=', mat
print 'mat . vec=', matmult(mat, vec)