# Symbolic matrices

How does one declare a matrix of specific symbolic dimension? For instance, if $$A,B,C,D$$ are four $$n\times n$$ matrices, $$M$$ is the block matrix $$M=\begin{bmatrix} A & B \\ C & D \end{bmatrix},$$ and $$J$$ is the symplectic matrix $$J=\begin{bmatrix} 0_n & I_n \\ -I_n & 0_n \end{bmatrix},$$ I would like to have Mathematica tell me that $$MJM^\top-J=\begin{bmatrix} AB^\top-BA^\top & AD^\top-BC^\top -I_n \\ CB^\top - DA^\top + I_n & CD^\top - DC^\top \end{bmatrix}.$$

Define non-commutative multiplication of a pair of 2x2 block-matrices.

mul[{{a11_, a12_}, {a21_, a22_}}, {{b11_, b12_}, {b21_, b22_}}] :=
{{a11 ** b11 + a12 ** b21, a11 ** b12 + a12 ** b22},
{a21 ** b11 + a22 ** b21, a21 ** b12 + a22 ** b22}};


Define the transpose of a 2x2 block-matrix.

trans[{{a11_, a12_}, {a21_, a22_}}] := {{a11^T, a21^T}, {a12^T, a22^T}};


Define various simplification rules. There are more rules here than are needed to solve this problem.

Unprotect[NonCommutativeMultiply];
id ** u_ := u; u_ ** id := u;
u_ ** (-v_) := -u ** v; (-u_) ** v_ := -u ** v;
(u_ + v_) ** w_ := u ** w + v ** w; w_ ** (u_ + v_) := w ** u + w ** v;
0 ** u_ := 0; u_ ** 0 := 0;
Protect[NonCommutativeMultiply];


Define the block-matrices given in the original question.

m = {{a, b}, {c, d}};
j = {{0, id}, {-id, 0}};


Evaluate the expression given in the original question. This generates the result quoted in the original question.

mul[mul[m, j], trans[m]] - j // MatrixForm

• That is neat, but a lot of work. There are still quite a few things to implement (scalar multiplication, block inverse, block-matrices with greater sizes than 2x2, checking dimensions are conformal, block determinant, etc), but I thought this type of computation would already be doable without having to define everything from the ground up. Commented Nov 17, 2023 at 23:32
• I agree with everything you said there. My solution above is slimmed-down for the purposes of answering your specific question, and it shows what can be done by defining your own simplification rules. Adding in all the extra stuff to generalise it would have made it obscure. However, there is the NCAlgebra package for doing non-commutative algebra that might interest you (see mathweb.ucsd.edu/~ncalg). Commented Nov 18, 2023 at 0:02
• Right, definitely. This package sounds promising, Chapter 4.7. deals with matrices "NCAlgebra has many commands for manipulating matrices with noncommutative entries. Think block-matrices.". Commented Nov 18, 2023 at 0:47