1

I have 2 multidimensional arrays. I want to multiply those arrays.

My both arrays have shape :

shape : (3, 100)

I want to convert matlab code :

sum(q1.*q2)

to

np.dot(q1, q2)

gives me output :

ValueError: objects are not aligned
2
  • 1
    np.dot is matrix multiply, numpy uses * for element wise multiply. Commented Jan 21, 2014 at 5:46
  • @BiRico -- That was my first thought as well (but I wasn't confident enough in my matlab to know for sure what the .* operator was doing). Why not post it as an answer? Commented Jan 21, 2014 at 5:50

2 Answers 2

2

Use Matrix element wise product * instead of dot product

Here is a sample run with a reduced dimension

Implementation

A = np.random.randint(5,size=(3,4))
B = np.random.randint(5,size=(3,4))
result = A * B

Demo

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

Comments

1

My installation of Octave, when asked to do

sum(a .* b)

with a and b having shape (3, 100), returns an array of shape (1, 100). The exact equivalent in numpy would be:

np.sum(a * b, axis=0)

which returns an array of shape (100,), or if you want to keep the dimensions of size 1:

np.sum(a * b, axis=0, keepdims=True)

You can get the same result, possibly faster, using np.einsum:

np.einsum('ij,ij->j', a, b)

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.