Saikiran
Saikiran

Reputation: 776

Issue with numpy matrix multiplication

I'm trying to multiply two matrices of dimensions (17,2) by transposing one of the matrices

Here is example p1

    p1 = [[ 0.15520622 -0.92034567]
 [ 0.43294367 -1.05921439]
 [ 0.7569707  -1.15179354]
 [ 1.08099772 -1.15179354]
 [ 1.35873517 -0.96663524]
 [-1.51121847 -0.64260822]
 [-1.32606018 -0.87405609]
 [-1.00203315 -0.96663524]
 [-0.67800613 -0.96663524]
 [-0.3539791  -0.87405609]
 [ 0.89583942  1.02381648]
 [ 0.66439155  1.3478435 ]
 [ 0.3866541   1.48671223]
 [ 0.15520622  1.5330018 ]
 [-0.07624165  1.5330018 ]
 [-0.3539791   1.44042265]
 [-0.58542698  1.20897478]]

here is another example matrix p2

 p2 = [[ 0.20932473 -0.90029958]
 [ 0.53753779 -1.03849455]
 [ 0.88302521 -1.10759204]
 [ 1.24578701 -1.02122018]
 [ 1.47035383 -0.77937898]
 [-1.46628927 -0.69300713]
 [-1.29354556 -0.9521227 ]
 [-0.96533251 -1.03849455]
 [-0.63711946 -1.00394581]
 [-0.3089064  -0.90029958]
 [ 0.86575084  1.06897874]
 [ 0.55481216  1.37991742]
 [ 0.26114785  1.50083802]
 [ 0.03658102  1.51811239]
 [-0.1879858   1.50083802]
 [-0.46437574  1.37991742]
 [-0.74076568  1.08625311]]

I'm trying to multiply them using numpy

import numpy

print(p1.T * p2)

But I'm getting the following error

operands could not be broadcast together with shapes (2,17) (17,2) 

This is the expected matrix multiplication output

[[11.58117944  2.21072324]
 [-0.51754442 22.28728876]]

Where exactly am I going wrong

Upvotes: 0

Views: 1284

Answers (3)

Saikiran
Saikiran

Reputation: 776

Sorry for a vague question. Initially, I was getting p1 and p2 values from numpy matrix. I later stored them in json file as list for optimization by using

.tolist()

method and was reading it back as numpy array using

numpy.array()

method which is apparently wrong..I changed my code to read the numpy array using

numpy.matrix()

method which seems to solve the issue. Hope this helps someone

Upvotes: 0

lei guo
lei guo

Reputation: 11

Matrix multiplication is done with np.dot(p1.T,p2), because A * B means matrix elements-wise multiply.

Upvotes: 1

zipa
zipa

Reputation: 27869

So you should use np.dot:

p1.T.dot(p2)

Upvotes: 0

Related Questions