George Tahamo
George Tahamo

Reputation: 25

Matrix multiplication strange error

This is the problem I'm struggling from like 3 hours now ;/ In python with numpy I do simple multiplication like:

matrix.T * matrix

, where m is my matrix but even if in my brain everything is ok ( sizes match properly) I keep on getting error message:

operands could not be broadcast together with shapes (5,20) (20,5) 

Why is that? Doesn't 20 match 20 ? What's wrong with me ;D ?

Thanks in advance

Upvotes: 0

Views: 637

Answers (2)

Moses Koledoye
Moses Koledoye

Reputation: 78536

Your matrix variable is a misnomer. What you have is a multidimensional array.

You can simply use np.dot to multiply your arrays:

matrix.T.dot(matrix)

If you actually had matrices created with np.matrix, that multiplication will work without problems

Upvotes: 3

user2357112
user2357112

Reputation: 280182

Matrix multiplication is the dot method in NumPy, or the @ operator if you're on sufficiently recent Python and NumPy:

matrix.T.dot(matrix)

or

matrix.T @ matrix

or (if you have sufficiently recent NumPy but insufficiently recent Python)

np.matmul(matrix.T, matrix)

Note that NumPy has a matrix class that behaves differently, but you should never use it.

Upvotes: 3

Related Questions