I have a simple issue. I want to shorten the expression of the kronecker product
a=np.matrix('1 0; 0 1')
b=np.matrix('1 0; 0 1')
C=np.kron(a,b)
to something like this
C=a.k(b)
I have been flogging google for a while, but I do not quite find the solution to this. I understand that there are workarounds which work perfectly fine, but I would like to understand how to add a function to a numpy object like this. Or any object. I want to learn, not do.
Any ideas? Thanks in advance!
If you don't want to subclass the Matrix, you can monkeypatch your method at runtime. That means that you just create the function you want to add to the matrix class and than assign it to the attribute name of the class you want the method name to be, in this instance k
. This works, because in Python, functions are first class objects, meaning that you can assign them to a variable (or class attribute), which is equivalent to defining the function in the actual class.
def kron(self, other):
return np.kron(self, other)
np.matrix.k = kron
After that, you can call:
>>> a.k(b)
matrix([[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
You can read more about monkeypatching here: What is monkey patching?