Search code examples
pythonarraysnumpyvectormatrix-multiplication

multiply many 2d arrays by vector using the previous result of the array


a = np.array([0, 0, 1000])

b = np.array([[0.1,0.5,0.4],[0.2,0,0.8],[0.1,0.2,0.7]])

c= np.array([[0,0.5,0.5],[0.3,0,0.7],[0.1,0.4,0.5]])

d= np.array([[0.3,0.5,0.2],[0.4,0.3,0.3],[0.1,0.3,0.6]])

I have this vector (a) that I need to multiply by many 2d arrays(b,c,d). How can I write a loop that takes a and multiplies by b and then uses the result, to multiply by c ,and then uses that result to multiply by d.

I am currently doing this

result=np.dot(a,b)

result2=np.dot(result,c)

result3=np.dot(result2,d)

But i need to be able to loop through all as I have many vectors and matrices.

**edit np.linalg.multi_dot works for this case, but I need to get the output of each array like this

array([130., 330., 540.])
array([225., 326., 449.])```

Solution

  • You can use the multi_dot function:

    np.linalg.multi_dot([a, b, c, d])