0
$\begingroup$

I want the product of matrix objects to be evaluated to the matrix object of dot products of the arguments, but only if the matrices commute. Why this does not work?

Unprotect[Times];
Matrix[x_] Matrix[y_] ^= Matrix[x . y] /; x . y == y . x  ;
Protect[Times];
$\endgroup$
4
  • $\begingroup$ This does not work because "Matrix" is not a defined word. A 2D e.g. matrix is written {{x11,x12},{x21,x22}} $\endgroup$ Commented Nov 2, 2022 at 19:40
  • $\begingroup$ @DanielHuber yes, it is not a defined symbol, but I want it behave this way. $\endgroup$
    – Anixx
    Commented Nov 2, 2022 at 19:41
  • $\begingroup$ It is not necessary to Unprotect and Protect Times. Use TagSetDelayed rather than TagSet. Matrix /: Matrix[x_] * Matrix[y_] := Matrix[x.y] /; x.y == y.x; $\endgroup$
    – Bob Hanlon
    Commented Nov 2, 2022 at 20:48
  • $\begingroup$ @BobHanlon thanks $\endgroup$
    – Anixx
    Commented Nov 2, 2022 at 20:57

1 Answer 1

1
$\begingroup$

If you want to define "Matrix" as a new Atom, your approach works.

E.g. let us define matrices a0 and a1 that commute:

a0 = RandomReal[{-1, 1}, {2, 2}];
a1 = a0 . a0;

and also a matrix that does not commute:

b = RandomReal[{-1, 1}, {2, 2}];

If we now define "Matrix":

Clear[Matrix]
Unprotect[Times];
Matrix[x_] Matrix[y_] /; x . y == y . x ^= Matrix[x . y];
Protect[Times];

We get for the product of 2 commuting matrices:

Matrix[a0] Matrix[a1]
(* Matrix[{{0.090018, -0.15005}, {-0.276659, 0.0619167}}] *)

and for non-commuting matrices:

Matrix[a0] Matrix[b]
(* Matrix[{{-0.725916, -0.626387}, {-0.553722, -0.871338}}] \
Matrix[{{0.114884, -0.425647}, {-0.784798, 0.0351695}}] *) 
$\endgroup$
1
  • 1
    $\begingroup$ Oh, I had wron order in the condition, thanks! $\endgroup$
    – Anixx
    Commented Nov 2, 2022 at 20:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.