In Mathematica, often an expression involving matrices will encounter dimension mismatch errors, like we are multiplying a 3x2 matrix to a 3x4 matrix. Below we define a new symbol Dim, which can be passed through your algorithm as a fake parameter to detect errors.
Dim /: Dot[Dim[{x_, y_}], z_] /;
MatrixQ[z] :=
(checkEq[y, Dimensions[z][[1]]];
Dim[{x, Dimensions[z][[2]]}]);
This method can handle most matrix operations, but failed on Table, which seems quite special. In fact, I failed to pattern match with Table by writing:
Dim /: Times[Dim[{x_, y_}], Table[z_]] := Dim[x, y];(*incorrect, just for syntax*)
Dim /: Times[Table[z_], Dim[{x_, y_}]] := Dim[x, y];
The expected result should be:
Dim[{3, 2}] Table[Sin[i + j], {i, 3}, {j, 2}] == Dim[{3, 2}]
But now Dim is multiplied over every element of table and it returns:
{{Dim[{3, 2}] Sin[2], Dim[{3, 2}] Sin[3]}, {Dim[{3, 2}] Sin[3], Dim[{3, 2}] Sin[4]}, {Dim[{3, 2}] Sin[4], Dim[{3, 2}] Sin[5]}} == Dim[{3, 2}]
Full code:
Clear[Dim];
checkEq =
Function[{x, y},
If[x != y, Print[ToString[x] <> "!=" <> ToString[y]]; Abort[]]];
Dim /: Dimensions[Dim[x_]] := x;
Dim /: MatrixQ[Dim[_]] := True;
Dim /: Dot[Dim[{x_, y_}], z_] /;
MatrixQ[z] :=
(checkEq[y, Dimensions[z][[1]]];
Dim[{x, Dimensions[z][[2]]}]);
Dim /: Dot[z_, Dim[{x_, y_}]] /;
MatrixQ[z] :=
(checkEq[Dimensions[z][[2]], x];
Dim[{Dimensions[z][[1]], y}]);
Dim /: Times[z_, Dim[{x_, y_}]] /;
MatrixQ[z] :=
(checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
Dim /: Times[Dim[{x_, y_}], z_] /;
MatrixQ[z] :=
(checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
Dim /: Plus[z_, Dim[{x_, y_}]] /;
MatrixQ[z] :=
(checkEq[Dimensions[z], {x, y}]; Dim[{x, y}]);
(*Dim/:Dot[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[y,z];Dim[{x,w}]);
Dim/:Times[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);\
Dim/:Plus[Dim[{x_,y_}],Dim[{z_,w_}]]:=(checkEq[x,z];checkEq[y,w];Dim[{x,y}]);*)
Dim /: Times[x_, Dim[{y_, z_}]] /; NumberQ[x] := Dim[{y, z}];
(*Below are tests that should return true.*)
MatrixQ[Dim[{2, 3}]]
Dimensions@Dim[{1, 2}] == {1, 2}
Dim[{3, 2}].Dim[{2, 4}] == Dim[{3, 4}]
Dim[{3, 2}].RandomReal[1, {2, 4}] == Dim[{3, 4}]
RandomReal[1, {2, 4}].Dim[{4, 3}] == Dim[{2, 3}]
Dim[{3, 2}] Dim[{3, 2}] == Dim[{3, 2}]
2 Dim[{3, 2}] == Dim[{3, 2}]
Dim[{3, 2}] - Dim[{3, 2}] == Dim[{3, 2}]
(*Below are tests that should raise errors.*)
Dim[{3, 2}] - Dim[{2, 4}]
Dim[{3, 2}] Dim[{2, 4}]
Dim[{5, 3}].Dim[{2, 4}]