matrix multiplication is strange in numpy(m*m equals m.dot(m)!!!)
Question:
I find a strange problem in numpy:
if m is a matrix, the results of m1*m2 is always the same as m1.dot(m2)!!!
So how can I multipy two matrixes by elements?(such as m1.*m2 in matlab)
Answers:
This is by-design. Link
For matrix
, ‘*’ means matrix multiplication, and the multiply()
function is used for element-wise multiplication.
e.g.
>>> import numpy
>>> numpy.multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
array([[ 5, 12],
[21, 32]])
If you multiply matrices (of type numpy.matrix
), NumPy assumes you want matrix multiplication, which doesn’t really seem that strange to me. To multiply element-wise, either use arrays (numpy.array
) instead of matrices, or use numpy.multiply()
.
I find a strange problem in numpy:
if m is a matrix, the results of m1*m2 is always the same as m1.dot(m2)!!!
So how can I multipy two matrixes by elements?(such as m1.*m2 in matlab)
This is by-design. Link
For
matrix
, ‘*’ means matrix multiplication, and themultiply()
function is used for element-wise multiplication.
e.g.
>>> import numpy
>>> numpy.multiply([[1, 2], [3, 4]], [[5, 6], [7, 8]])
array([[ 5, 12],
[21, 32]])
If you multiply matrices (of type numpy.matrix
), NumPy assumes you want matrix multiplication, which doesn’t really seem that strange to me. To multiply element-wise, either use arrays (numpy.array
) instead of matrices, or use numpy.multiply()
.