Reputation: 19164
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
Upvotes: 1
Views: 2342
Reputation: 67417
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)
Upvotes: 1
Reputation: 63707
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]])
Upvotes: 2