Guides/Language FAQ/Matrix Product

From J Wiki
Jump to navigation Jump to search

Why doesn't "A * B" matrix multiply the two matrices A and B?

The problem is:

   ]A =: 2 3 $ 4 3 8 6 5 3
4 3 8
6 5 3
   ]B =: 3 2 $ 5 4 9 6 4 2
5 4
9 6
4 2
   A * B
|length error
|   A    *B

A J array is not the same thing as a matrix in mathematics. A mathematical matrix is a two-dimensional array that follows the rules of scalar multiplication and matrix multiplication and addition. A J array can have any number of dimensions, and is not restricted to matrix operations.

The length error above is caused because, in J, for A * B to work, the frame of one must be a prefix of the frame of another, see JDic:dictb. In particular, if A and B are both matrices, then * is applied cell by cell and the shapes must match.

J does have verbs that perform matrix operations: +/ . * for matrix multiply, %. for matrix inverse/matrix divide, -/ . * for determinant, and 128!:0 and 128!:1 for special matrix operations. To find the matrix product of A and B, use

   A +/ . * B
79 50
87 60



Contributed by Richard Hill