as stated in the title I want to make a calculation where instead of multiplying corresponding elements I binary XOR them and then add them. Example for illustration:
EDIT: The big picture above IS the calculation but here we go: Take first row from the left [1 0 1] and first column from top matrix [1 0 0]. 1 XOR 1 = 0, 0 XOR 0 = 0, 1 XOR 0 = 1. Add them all 0 + 0 + 1 = 1. First row from the left [1 0 1], second column [0 0 0]: 1 XOR 0 = 1, 0 XOR 0 = 0, 1 XOR 0 = 1. Add them all 1 + 0 + 1 = 2. And so on
Is it possible to do that in numpy?
The numpy. multiply() method takes two matrices as inputs and performs element-wise multiplication on them. Element-wise multiplication, or Hadamard Product, multiples every element of the first matrix by the equivalent element in the second matrix. When using this method, both matrices should have the same dimensions.
multiply() technique will be used to do the element-wise multiplication of matrices in Python. The NumPy library's np. multiply(x1, x2) method receives two matrices as input and executes element-wise multiplication over them before returning the resultant matrix. We must send the two matrices as input to the np.
multiply() in Python. numpy. multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise.
NumPy matrix multiplication can be done by the following three methods. multiply (): element-wise matrix multiplication. matmul (): matrix product of two arrays. dot (): dot product of two arrays. 1. NumPy Matrix Multiplication Element Wise If you want element-wise matrix multiplication, you can use multiply () function.
Finally, if you have to multiply a scalar value and n-dimensional array, then use np.dot (). np.dot () is a specialisation of np.matmul () and np.multiply () functions. This is a guide to Matrix Multiplication in NumPy.
Using numpy.multiply () method. The 2D multiplication is the same as 1 D element wise multiplication. There is a question among readers that which method should you choose. As you already know the faster method is mostly preferred. So if you will use the multiply () method then you will get faster results.
However, if one dimension of a matrix is missing, NumPy would broadcast it to match the shape of the other matrix. In fact, matrix multiplication with a scalar also involves the broadcasting of the scalar value to a matrix of the shape equal to the matrix operand in the multiplication.
Try this:
M1 = np.array([[1, 0, 0], [0, 0, 0], [0, 0, 0]])
M2 = np.array([[1, 0, 1], [0, 0, 1], [1, 1, 1]])
(M1 ^ M2[:,None]).sum(-1)
Output:
array([[1, 2, 2],
[2, 1, 1],
[2, 3, 3]])
EDIT
If you want to preallocate memory:
intermediary = np.empty((3,3,3), dtype=np.int32)
np.bitwise_xor(M1, M2[:,None], out=intermediary).sum(-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With