Viss
Viss

Reputation: 47

Numpy Matrix Multiplication Explanation

I am working through some math exercises and I do not understand why my numpy matrix multiplication is not working.

So I have:

t = np.array([[6,-1],[2,3]])
c = np.array([[1,1], [1,2]])
cinv = np.linalg.inv(c)

Which gives me:

t:
   [[ 6 -1]
    [ 2  3]]
c:
   [[1 1]
    [1 2]]
cinv:
   [[ 2. -1.]
    [-1.  1.]]

Now when I run my equation I get the following:

cinv*t*c
array([[12.,  1.],
       [-2.,  6.]])

Which this is not correct. I did it over a couple times and the correct answer is (5,0)(0,4). Why is the multiplication being carried out by position instead of row * column?

Can someone help me out with what I am doing wrong here?

Upvotes: 0

Views: 53

Answers (1)

M Z
M Z

Reputation: 4799

Using * does elementwise multiplication, not dot product. Use @ for a dot product multiplication. This is Numpy's choice for overloading operators. In fact, in the original Python design however, @ was designated for matrix multiplication, which is probably why this is the case.

import numpy as np


t = np.array([[6,-1],[2,3]])
c = np.array([[1,1], [1,2]])
cinv = np.linalg.inv(c)

print(cinv@t@c)
"""
Result:
[[5. 0.]
 [0. 4.]]
"""

Often times, I find it a lot easier to read to use strict functions and not the overloaded operators (though they can get crowded fast).

np.dot(A, B) or A.dot(B) work as dot products

Here's some documentation on what each symbol does, explicitly.

Upvotes: 1

Related Questions