For ndarrays, *
is elementwise multiplication (Hadamard product) while for numpy matrix objects, it is wrapper for np.dot
(source code).
As the accepted answer mentions, np.multiply
always returns an elementwise multiplication. Notably, it preserves the type of the object, if a matrix object is passed, the returned object will be matrix; if ndarrays are passed, an ndarray is returned.
If you have a np.matrix
object, then you can convert it into an ndarray (via .A
attribute) and use *
for elementwise multiplication. However, note that unlike np.multiply
which preserves the matrix
type, it returns an ndarray
(because we converted to ndarray before multiplication).
a = np.matrix([[1, 2], [3, 4]])
b = np.matrix([[5, 6], [7, 8]])
c = a.A * b.A
# array([[ 5, 12],
# [21, 32]])
Then again, matrix
is not recommended by the library itself and once it's removed from numpy, this answer (and arguably the question as well) will probably be obsolete.
a
andb
aren't NumPy's matrix type? With this class,*
returns the inner product, not element-wise. But for the usualndarray
class,*
means element-wise product. – Ardya
andb
numpy arrays? Also, in your question above, you are usingx
andy
for computation instead ofa
andb
. Is that just a typo? – Splashdown@
for matrix multiplication with numpy arrays, which means there should be absolutely no good reason to use matrices over arrays. – Macaroona
andb
are lists. They will work innp.dot
; but not ina*b
. If you usenp.array(a)
ornp.matrix(a)
,*
works but with different results. – Artefactnp.array(a)
andnp.array(b)
. Then, simplea*b
works. Note that if the numbers are large, you should usenp.array(a, dtype=np.int64)
to have right outputs. – Lowrance