0

I am so confused about Numpy array. Let's say I have two Numpy arrays.

a = np.array([[1,2], [3,4], [5,6]])
b = np.array([[1,10], [1, 10]])

My interpretations of a and b are 3x2 and 2x2 matrices, i.e,

a = 1 2    b = 1 10
    3 4        1 10
    5 6

Then, I thought it should be fine to do a * b since it is a multiplication of 3x2 and 2x2 matrices. However, it was not possible and I had to use a.dot(b).

Given this fact, I think my intepretation of Numpy array is not right. Can anyone let me know how I should think of Numpy array? I know that I can do a*b if I convert a and b into np.matrix. However, looking at other's code, it seems that people are just fine to use Numpy array as matrix, so I wonder how I should understand Numpy array in terms of matrix.

4
  • If you are on Python 3.5, you can use a @ b to do what you want. a * b does an elementwise multiplication. Commented Nov 8, 2016 at 4:27
  • Also, to check if you're dimensions match, you can try .shape to see the dimensions. Then, if you find out that the dimensions don't match, you can transpose it. :) Commented Nov 8, 2016 at 4:30
  • Both kinds of multiplicatin are useful. Look at MATLAB code, you'll see both a*b and a.*b. Commented Nov 8, 2016 at 4:30
  • Why does having to use .dot bother you? Commented Nov 8, 2016 at 5:09

2 Answers 2

2

For numpy arrays, the * operator is used for element by element multiplication of arrays. This is only well defined if both arrays have the same dimensions. To illuminate *-multiplication, note that element by element multiplication with the identity matrix will not return the same matrix

>>> I = np.array([[1,0],[0,1]])
>>> B = np.array([[1,2],[3,4]])
>>> I*B
array([[ 1, 0], 
       [ 0, 4]])

Using the numpy function dot(a,b) produces the typical matrix multiplication.

>>> dot(I,B)
array([[ 1, 2],
       [ 3, 4]])
Sign up to request clarification or add additional context in comments.

2 Comments

How is there a 10 on your result (I*B) 2nd column, 2nd line?
Thanks for the catch! I accidentally copied and pasted the wrong multiplication from my terminal. Error corrected above.
1

np.dot is probably what you're looking for?

a = np.array([[1,2], [3,4], [5,6]])

b = np.array([[1,10], [1, 10]])

np.dot(a,b)

Out[6]:
array([[  3,  30],
       [  7,  70],
       [ 11, 110]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.