hatmatrix
hatmatrix

Reputation: 44972

numpy multiple matrix multiplication

If I have a matrix product like $(x-\mu)^T \Sigma^{-1} (x-\mu)$, is the way to write this for numpy arrays would be reduce(numpy.dot,((x-mu).T, scipy.linalg.inv(Sigma), x-mu))? Matlab and R syntax is so much simpler that it seems a bit odd for numpy to not have an equivalent operator syntax.

Upvotes: 1

Views: 609

Answers (3)

pv.
pv.

Reputation: 35155

You can also write (Numpy >= 1.4 or so)

from scipy.linalg import inv

(x - mu).T.dot(inv(Sigma)).dot(x - mu)

As mentioned in the other answer, the limited operator syntax is due to the restricted number of operators available in Python.

Upvotes: 1

ChrisB
ChrisB

Reputation: 4718

The main issue is that * is already defined as elementwise multiplication for numpy arrays, and there is no other obvious operator left for matrix multiplication. The solution, as Pierre suggests, is to convert to numpy matrices, where * means matrix multiplication.

There have been a few proposals to add new operator types to Python (PEP 225, for example) which would allow something like ~* to represent matrix multiplication.

Upvotes: 1

Pierre GM
Pierre GM

Reputation: 20359

You could also try:

x = x.view(np.matrix)
isigma = scipy.linalg.inv(Sigma).view(np.matrix)
result = (x-mu).T * isigma * (x-mu)

By taking a view of your arrays as matrices, you get to use the .__mul__ operator of np.matrix which performs your matrix multiplication when you use *.

Upvotes: 4

Related Questions