Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy matrix multiplication with custom dot product

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?

like image 433
Wai Yip Tung Avatar asked Oct 09 '13 17:10

Wai Yip Tung


People also ask

How do you multiply a matrix by dot product?

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).

Does NP dot do matrix multiplication?

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.

What is two dot product array?

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.


1 Answers

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.

like image 168
hpaulj Avatar answered Sep 21 '22 01:09

hpaulj