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

1.2k views Asked by At

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?

2

There are 2 answers

1
Lobachevsky On BEST ANSWER

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

0
ngn On

Inner product can be defined as:

A f.g B   ←→   f/¨ (⊂[¯1+⍴⍴A]A) ∘.g ⊂[0]B

That is: cut A into slices along its last axis, do the same with B along its first axis, then combine each slice from A with each slice from B using g, and finally perform a reduction using f.

If A and B are matrices, the slices will be the rows of A and the columns of B:

┌───┐     ┌───┐
│0 1│     │4 5│
│   │ +.× │   │
│2 3│     │6 7│
└───┘     └───┘

     ┌───┐     ┌─┬─┐
     │0 1│     │4│5│
+/¨  ├───┤ ∘.× │ │ │
     │2 3│     │6│7│
     └───┘     └─┴─┘

     ┌─────────┬─────────┐
     │0 1 × 4 6│0 1 × 5 7│
+/¨  ├─────────┼─────────┤
     │2 3 × 4 6│2 3 × 5 7│
     └─────────┴─────────┘

┌────────────┬────────────┐
│+/ 0 1 × 4 6│+/ 0 1 × 5 7│
├────────────┼────────────┤
│+/ 2 3 × 4 6│+/ 2 3 × 5 7│
└────────────┴────────────┘

┌─────┐
│ 6  7│
│     │
│26 31│
└─────┘

If A and B are vectors, then the slices will be A and B themselves, and you get

A +.× B   ←→   +/ A×B        ⍝ if A and B are vectors

In any case, for inner product to work, A's last axis needs to match the length of B's first axis.