Search code examples
pythonnumpymatrixmatrix-multiplication

Numpy dot() function equivalent


This question is just out of pure curiosity. Suppose I have 2 matrices a and b.

a=np.array([[1, 2],
            [2, 3],
            [4, 5]])

b=np.array([[1, 2, 3, 4],
            [2, 3, 4, 5]])

To find their dot product, I might use np.dot(a,b). But is there any other way to do this? I am not asking for any other alias functions. But maybe another way to do this like np.sum(a*b, axis=1) (I know that doesn't work, it is just an example). And what if I have a 3-D matrix? Is there any other way to compute their dot product as well (without using any functions)?

Thanks in advance!


Solution

  • In [66]: a=np.array([[1, 2],
        ...:             [2, 3],
        ...:             [4, 5]])
        ...: 
        ...: b=np.array([[1, 2, 3, 4],
        ...:             [2, 3, 4, 5]])
        ...: 
        ...:             
    In [67]: np.dot(a,b)
    Out[67]: 
    array([[ 5,  8, 11, 14],
           [ 8, 13, 18, 23],
           [14, 23, 32, 41]])
    In [68]: a@b
    Out[68]: 
    array([[ 5,  8, 11, 14],
           [ 8, 13, 18, 23],
           [14, 23, 32, 41]])
    In [69]: np.einsum('ij,jk',a,b)
    Out[69]: 
    array([[ 5,  8, 11, 14],
           [ 8, 13, 18, 23],
           [14, 23, 32, 41]])
    

    Broadcasted multiply and sum:

    In [71]: (a[:,:,None]*b[None,:,:]).sum(axis=1)
    Out[71]: 
    array([[ 5,  8, 11, 14],
           [ 8, 13, 18, 23],
           [14, 23, 32, 41]])
    In [72]: (a[:,:,None]*b[None,:,:]).shape
    Out[72]: (3, 2, 4)