# Quaternionic matrix multiplication

What would be the correct way to multiply matrices with quaternionic values in Mathematica? For example

<< Quaternions
{{Quaternion[7, 0, 0, 0],
Quaternion[0, 1, 1, 0]}, {Quaternion[0, 0, 1, 7],
Quaternion[0, 5, 0, 1]}}
(*Both %.% and %**% seem to not be correct*)
• Denoting q = {{Quaternion[7, 0, 0, 0], Quaternion[0, 1, 1, 0]}, {Quaternion[0, 0, 1, 7], Quaternion[0, 5, 0, 1]}}, then InternalInheritedBlock[{Times}, Times//Attributes={Flat,Listable,NumericFunction,OneIdentity,Protected}; q . q/.{Times->NonCommutativeMultiply} ] and Outer[NonCommutativeMultiply,q,q]//TensorContract[#,{{2,3}}]& should both give the matrix product q.q. Commented Sep 11, 2022 at 13:06

You could define a new function that multiplies quaternion matrices like:

qmatmul[q1_, q2_] := Inner[NonCommutativeMultiply, q1, q2, Plus]

Let us test this by:

q = {{Quaternion[7, 0, 0, 0], Quaternion[0, 1, 1, 0]},
{Quaternion[0, 0, 1, 7], Quaternion[0, 5, 0, 1]}};

qmatmul[q, q]

(* Out:
{{Quaternion[48, 7, -7, 1], Quaternion[-5, 8, 6, -5]},
{Quaternion[-7, -1, -28, 54], Quaternion[-27, -7, 7, -1]}} *)

To check if this is correct, we may do the same calculation by "hand". The non-commuting can be simulated by choosing elements that are lexicographic in the correct order (e.g. $$a_{ij}$$ and $$b_{ij}$$):

ta = {{a11, a12}, {a21, a22}};
tb = {{b11, b12}, {b21, b22}};
ta . tb /. {Times -> NonCommutativeMultiply, x_^2 -> x ** x} /.