Reputation: 685
I am trying to calculate the product:
tA*M*B
where A, B are two vectors and M is a squared matrix, tA is the transposed A. The result should be a number.
Numpy has the dot()
function that multiplies arrays and matrix: is there a way I can use it to calculate my product in a single blow?
I am using python 2.6
Upvotes: 0
Views: 2253
Reputation: 231385
np.einsum
gives more control over dot
operations. There's some debate, though, about when it is faster or slow than np.dot
, and whether it consumes too much memory (when the matricies are very big
A=np.arange(1,4)
B=10*np.arange(3,6)
M=np.arange(9).reshape(3,3)
np.dot(A,np.dot(M,B))
np.einsum('i,ij,j',A,M,B)
Upvotes: 1
Reputation: 8126
You can use the reduce function
reduce(numpy.dot,[tA,M,B])
This is equivalent to
numpy.dot(numpy.dot(tA,M),B)
From the tutorial
reduce(function, sequence)
returns a single value constructed by calling the binary function function on the first two items of the sequence, then on the result and the next item, and so on.
An easy to understand example from the documentation is
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
calculates((((1+2)+3)+4)+5)
Whether it's worth using reduce
in your case is debatable. However it clarifies the code if you have a long string of matrix multiplications. Compare the following, equivalent lines of code that multiply tA, M1, M2, M3, and B together.
print numpy.dot(numpy.dot(numpy.dot(numpy.dot(tA,M1),M2),M3),B)
print reduce(numpy.dot,[tA,M1, M2, M3,B])
Upvotes: 2
Reputation: 7126
How about:
import numpy
#Generate Random Data
M = numpy.random.normal(0,1,9).reshape(3,3)
A = numpy.random.normal(0,1,3)
B = numpy.random.normal(0,1,3)
#The Operation
numpy.dot(A, numpy.dot(M,B) )
Upvotes: 2