Reputation: 30332
I am using Numpy's matlib
style matrices for a particular algorithm. This means that the multiplication operator *
performs the equivalent of an ndarray
's dot()
:
>>> import numpy.matlib as nm
>>> a = nm.asmatrix([[1,1,1],[1,1,1],[1,1,1]])
>>> b = nm.asmatrix([[1,0,0],[0,1,0],[0,0,1]])
>>> a * b
matrix([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
Is there a method to perform element-wise arithmetic, like the *
operator does on ndarray
s?
Upvotes: 1
Views: 163
Reputation: 353079
You could use np.multiply
:
>>> a = np.matrix(np.random.rand(3,3))
>>> b = np.matrix(np.random.rand(3,3))
>>> a * b
matrix([[ 1.29029129, 0.53126365, 2.12109815],
[ 0.99370991, 0.55737572, 1.9167072 ],
[ 0.76268194, 0.43509462, 1.48640178]])
>>> np.asarray(a) * np.asarray(b)
array([[ 0.67445535, 0.12609799, 0.7051103 ],
[ 0.00131878, 0.42079486, 0.5223201 ],
[ 0.65558303, 0.03020335, 0.16753354]])
>>> np.multiply(a, b)
matrix([[ 0.67445535, 0.12609799, 0.7051103 ],
[ 0.00131878, 0.42079486, 0.5223201 ],
[ 0.65558303, 0.03020335, 0.16753354]])
It's a little unusual to want to perform elementwise multiplication on the same object you're performing matrix multiplication on, but you probably already know that. :^) It might be worthwhile seeing if your algorithm has a nice np.einsum
description, though.
Upvotes: 1