5
$\begingroup$

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.

$\endgroup$
  • 3
    $\begingroup$ 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. $\endgroup$ – Kuba Feb 12 at 21:45
  • $\begingroup$ I understand it is how Mathematica works, yet I would not refer to this as "power". $\endgroup$ – infinitezero Feb 13 at 13:03
8
$\begingroup$

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}}

enter image description here

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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