# Define different actions for the same operator depending on the nature of its arguments

I am working with terms of the form

A**B1**B2


where A, B1, and B2 are at this point abstract operators and ** means NonCommutativeMultiply.

I'd like to manipulate these expressions at an abstract level, and then only later substitute explicit matrix operations. Specifically, $$A$$ will be a square matrix, while $$B1$$ and $$B2$$ will be commensurate vectors.

The trick is that at this point the specific meanings of the two occurrences of ** will change. Specifically, A ** B1 will become a matrix multiplication, and B1 ** B2 will become an outer product.

I'm using a package (NCAlgebra) to simplify the expressions at an abstract level, and I want the special handling of NonCommutativeMultiply to apply then. So it would be good if there were some way to create an operation that behaves in all respects as NonCommutativeMultiply (so that the package still recognizes it as such), except in a certain function of my design (so that it gets substituted for the correct explicit operation).

Is there a way I can accomplish this?

Edit: A perhaps-important complication is that in the general case, once made explicit the matrix dimensions will be such that the matrix multiplication A ** B1 will not be defined until the outer product B1 ** B2 has been performed.

• How are we supposed to distinguish between matrix multiplication and outer product? It looks the same to me. Mar 14, 2019 at 17:47
• Do you mean mathematically or in the code? Mathematically the two vectors are mapped by the outer product to a square matrix. In the code we would need to create a new function for at least one. I would like that function to behave as NonCommutativeMultiply, except when otherwise specified.
– AGML
Mar 14, 2019 at 17:49
• All I see is A**B1**B2 and the two ** look the same to me. How are we supposed to know that they are supposed to be different? Mar 14, 2019 at 17:52
• We of course cannot, at present. To solve the problem one of the two ** needs to be replaced by a new function. I have used ** in both cases because I want the new function to match the same existing patterns as ** would.
– AGML
Mar 14, 2019 at 17:53
• Alternatively, ** could be used in both cases, but the replacement rule could e.g. substitute an outer product only when the inner product is not defined, or something along those lines.
– AGML
Mar 14, 2019 at 17:54

If I understand your question correctly, then the ** can be given a definition to do what you want. This code may work for you

Unprotect[NonCommutativeMultiply];
ClearAll[NonCommutativeMultiply];
NonCommutativeMultiply[x_?NumericQ, y_?NumericQ] := x * y;
NonCommutativeMultiply[x_?MatrixQ, y_?MatrixQ] := x . y;
NonCommutativeMultiply[x_?ListQ, y_?ListQ] := Outer[Times, x, y];


You can add more checking in the code as you need to.

• Yes, that should work I think. Thank you!
– AGML
Mar 14, 2019 at 18:17