The default matrix multiplication is computed as
c[i,j] = sum(a[i,k] * b[k,j])
I am trying to use a custom formula instead of the dot product to get
c[i,j] = sum(a[i,k] == b[k,j])
Is there an efficient way to do this in numpy?
Multiplication of two matrices involves dot products between rows of first matrix and columns of the second matrix. The first step is the dot product between the first row of A and the first column of B. The result of this dot product is the element of resulting matrix at position [0,0] (i.e. first row, first column).
If both inputs are 1-dimensional arrays, np. dot() will compute the dot product of the inputs. If both inputs are 2-dimensional arrays, then np. dot() will perform matrix multiplication.
Dot product of two arrays. Specifically, If both a and b are 1-D arrays, it is inner product of vectors (without complex conjugation). If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
You could use broadcasting:
c = sum(a[...,np.newaxis]*b[np.newaxis,...],axis=1) # == np.dot(a,b)
c = sum(a[...,np.newaxis]==b[np.newaxis,...],axis=1)
I included the newaxis
in b
just make it clear how that array is expanded. There are other ways of adding dimensions to arrays (reshape, repeat, etc), but the effect is the same. Expand a
and b
to the same shape to do element by element multiplying (or ==), and then sum on the correct axis.
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