user3882
user3882

Reputation: 128

NumPy dot product of matrix and array

From numpy's documentation: https://numpy.org/doc/stable/reference/generated/numpy.dot.html#numpy.dot

numpy.dot(a, b, out=None)

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.

  • If either a or b is 0-D (scalar), it is equivalent to multiply and using numpy.multiply(a, b) or a * b is preferred.

  • If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b:

According to the 4th point, if we take the dot product of a 2-D array A and a 1-D array B, we should be taking the sum product over the columns of A and row of B since the last axis of A is the column, correct? Yet, when I tried this in the Python IDLE, here is my output:

>>> a
    array([[1, 2],
           [3, 4],
           [5, 6]])
>>> b
    [1, 2]
>>> a.dot(b)
    array([ 5, 11, 17])

I expected this to throw an error since the dimension of a's columns is greater than the dimension of b's row.

Upvotes: 4

Views: 4837

Answers (1)

orlp
orlp

Reputation: 117641

If a is an N-D array and b is a 1-D array, it is a sum product over the last axis of a and b.

The last axis of a has size 2:

>>> a.shape
(3, 2)

which matches bs size.

Remember: the first axis for multi-dimensional arrays in numpy is 'downward'. 1D arrays are displayed horizontally in numpy but I think it's usually better to think of them as vertical vectors instead. This is what's being computed:

enter image description here

Upvotes: 1

Related Questions