The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

189391 (4) [Avatar] Offline
I can't get the example code using vect_mat_mul() on p. 39 to work. I'm using Python 2.7.5 on Centos 7.
I've changed vars a & b to vect, matrix below. And, added len(vect).

   for i in range(len(vect)):
      output += (vect[i] * matrix[i])

The error I get is: TypeError: can't multiply sequence by non-int of type 'float'

Any suggestions? Thanks.
Prabh (4) [Avatar] Offline
Almost. I believe the way Andrew describes Matrices in the text is as a list of lists. vec[i] will be a number but matrix[i] will be a list. So your output is attempting to sum a number with a list and is throwing an error.

Try running the following:

def vec_Mat_Mult(Mat, Vec):

#Vec is a vector e.g. a list it will be a row vector with n rows
#Mat is a matrix e.g. a list of list matrix m x n
#Mat x Vec in m x 1 : (m x n) x (n x 1)

z = []

for i in range(len(Mat)): #loop over rows of matrix
assert (len(Vec) == len(Mat[i])) #the number of columns of Mat
#must match rows of Vec
wtd_sum = 0

for j in range(len(Vec)): #loop over columns of Matrix
wtd_sum += Mat[i][j]*Vec[j] #perform sum


return z

import numpy as np
vec = [1, 2, -20]
mat = [[1, 0, 0],
[0, 1, 1],
[-1, 2, 1],
[0, 0, 1]]
result = vec_Mat_Mult(mat, vec)
result_2 = np.array(mat).dot(np.array(vec))