Why does matrix multiplication in NumPy not call the __add__ method?
Question:
How does the method __mul__
in the class matrix
in NumPy work?
I want to implement a binary matrix multiplication, and I have a class Binary
:
class Binary(int):
def __init__(self, val):
if val != 0:
self.val = 1
else:
self.val = 0
def __add__(self, other):
print('add')
return self.val ^ other
def __radd__(self, other):
print('radd')
return self.val ^ other
My test:
from Binary import Binary
from numpy import matrix
i = Binary(1)
o = Binary(0)
a = matrix([i, i, o, i, i, o, o], dtype=Binary)
b = matrix([[o, o, i],
[o, i, o],
[o, i, i],
[i, o, o],
[i, o, i],
[i, i, o],
[i, i, i]], dtype=Binary)
print(a * b)
Result:
./test.py
[[2 1 2]]
The method __add__
is not used. Whereas there is a summation in matrix multiplication.
Answers:
how does multiplication differ for NumPy Matrix vs Array classes?
A*B is matrix multiplication, so more convenient for linear algebra. Make sure A & B are numpy arrays/matrix
How does the method __mul__
in the class matrix
in NumPy work?
I want to implement a binary matrix multiplication, and I have a class Binary
:
class Binary(int):
def __init__(self, val):
if val != 0:
self.val = 1
else:
self.val = 0
def __add__(self, other):
print('add')
return self.val ^ other
def __radd__(self, other):
print('radd')
return self.val ^ other
My test:
from Binary import Binary
from numpy import matrix
i = Binary(1)
o = Binary(0)
a = matrix([i, i, o, i, i, o, o], dtype=Binary)
b = matrix([[o, o, i],
[o, i, o],
[o, i, i],
[i, o, o],
[i, o, i],
[i, i, o],
[i, i, i]], dtype=Binary)
print(a * b)
Result:
./test.py
[[2 1 2]]
The method __add__
is not used. Whereas there is a summation in matrix multiplication.
how does multiplication differ for NumPy Matrix vs Array classes?
A*B is matrix multiplication, so more convenient for linear algebra. Make sure A & B are numpy arrays/matrix