aplinner-product

How come +.x in APL works for both matrices and vectors?


I do understand, it is basically multiplication reduced by adding, but what is the magic, making it work both for vectors and matrices.

For vector we can do something like +/ A x B instead with the same result. But this would not work for matrices, as x would just make a 2 2 matrix, and reducing it will result in 2 vector.

And doing matrix multiplication by the book, reducing each corresponding pow and column multiplication, would result in 2 2 matrix when doing the same to vectors.

So how does it work then?


Solution

  • For an inner product, whatever it may be, to work on two matrices, the last dimension of the left argument must match the first dimension of the right.

    Thus a matrix left argument whose shape is 5 2 3 2 will work with a matrix right argument whose shape is 2 3 9. 3 2 matches with 2 3. The shape of the result would be the shape of the left argument without the last element catenated with the shape of the right argumented without the first element, in this case, 5 2 3 3 9.

    In the case of vector arguments, the inner single dimension will do.

      (1 3 p 1 2 3) +.x 3 1 p 1 2 3         (matrices match)
    

    14

      1 2 3 +.x 3 1 p 1 2 3                
    

    14

      (1 3 p 1 2 3) +.x 1 2 3
    

    14

      1 2 3 +.x 1 2 3
    

    14