# Raise Warning/Error on invalid Matrix Addition and Multiplication

Consider the following code:

DiagonalMatrix[{1, 1, 1}] - 1


Mathematica interprets it in the way, that it substracts 1 from every matrix field while mathematically this operation is not defined. Is it possible to raise an error or at least a warning?

Furthermore

invalid = DiagonalMatrix[{1, 1, 1}].a
invalid /. a -> 4


produces an invalid matrix multiplication. I also want to raise an error or warning if this happens.

• That is the power of Mathematica. Instead of doing this I'd recomment to define your own set of matrix operations functions that will validate passed arguments and use them in your calculations.
– Kuba
Commented Feb 12, 2019 at 21:45
• I understand it is how Mathematica works, yet I would not refer to this as "power". Commented Feb 13, 2019 at 13:03

## 1 Answer

That would mean to remove the Listable attribute from Plus. You could do it as follows, but I would not recommend that.

Unprotect[Plus];
ClearAttributes[Plus, Listable];
Plus[_?MatrixQ, __?(! MatrixQ[#] &)] := $Failed  Now, you have a = IdentityMatrix[3]; Plus[a, a] Plus[a, 1]  {{2, 0, 0}, {0, 2, 0}, {0, 0, 2}}$Failed

Really, you should embrace the feature of listability rather than risking to break the whole system.

A better option might be to use the symbol CirclePlus instead; it has no built-in meaning. (You have to restart the kernel first in order to reset Plus to its original definition.)

CirclePlus::errorname = "Error message.";

(* This ensures that CirclePlus has in general the same functionality as Plus. *)
CirclePlus[x___] := Plus[x];

(* This this adds a special rule for undesired additions. *)
CirclePlus[a_?MatrixQ, b__?(! MatrixQ[#] &)] := (
Message[CirclePlus::errorname];
Plus[a, b]
)


Now you have

a = IdentityMatrix[3];
a⊕a
a⊕1


{{2, 0, 0}, {0, 2, 0}, {0, 0, 2}}

{{2, 1, 1}, {1, 2, 1}, {1, 1, 2}}