4
votes

I'm having a problem with multiplying two big matrices in python using numpy.

I have a (15,7) matrix and I want to multipy it by its transpose, i.e. AT(7,15)*A(15*7) and mathemeticaly this should work, but I get an error :

ValueError:shape mismatch:objects cannot be broadcast to a single shape I'm using numpy in Python. How can I get around this, anyone please help!

1
@agf: there's only one way to get the transpose in Numpy and it's hard to get wrong. The error message about broadcasting tells enough about the problem; if the OP hadn't transposed the matrix/array, they'd get an "objects not aligned" error, not this one. - Fred Foo
@larsmans Thanks, didn't read closely enough. - agf

1 Answers

14
votes

You've probably represented the matrices as arrays. You can either convert them to matrices with np.asmatrix, or use np.dot to do the matrix multiplication:

>>> X = np.random.rand(15 * 7).reshape((15, 7))
>>> X.T * X
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (7,15) (15,7)
>>> np.dot(X.T, X).shape
(7, 7)
>>> X = np.asmatrix(X)
>>> (X.T * X).shape
(7, 7)

One difference between arrays and matrices is that * on a matrix is matrix product, while on an array it's an element-wise product.