# Terms of expressions with non-commutative multiplication that meet the given criteria

There is the following expression:

expr=a^3**x**Transpose[x]**y+x+y**Transpose[y]**x**a^3+x**Transpose[y]


It is necessary to apply the Transpose[] to all terms in which include variable a^3.

I tried applying sequence of expressions for given variable __x^3__

expr /. __x^3___ -> Transpose[__x__]


But it seems to me that I chose not quite the right pattern. I ask for help, I will be grateful.

EDIT:

Also I try HoldPattern:

HoldPattern[a^3 ** __] -> Transpose[a^3 ** __]
expr/.%


Desired output:

out=Transpose[a^3**x**Transpose[x]**y+x+Transpose[y**Transpose[y]**x**a^3]+x**Transpose[y]

• Are you looking for something like expr /. Power[x_, 3] :> Transpose[x]? Could you include the output you would like to obtain from your expression expr? What "did not please you" in the last result specifically? May 23, 2022 at 11:49
• @MarcoB I need to transpose all the terms that are connected to this variable through non-commutative multiplication. See my edit please
– dtn
May 23, 2022 at 12:34
• The rule NonCommutativeMultiply[x___, a^3, y___] :>Transpose[NonCommutativeMultiply[x, a^3, y]] does the trick?!
– N0va
May 23, 2022 at 12:48

I am assuming that out was missing a closing bracket and should look like the following:

out =
Transpose[a^3 ** x ** Transpose[x] ** y] +
x +
Transpose[y ** Transpose[y] ** x ** a^3] +
x ** Transpose[y]


Here are two pretty similar approaches to achieve that:

rule1 = expr /.
NonCommutativeMultiply[x___, a^3, y___] :>
Transpose[NonCommutativeMultiply[x, a^3, y]];

rule2 = expr /. x_NonCommutativeMultiply?(MemberQ[#, a^3] &) :> Transpose[x];

rule1 == rule2 == out
(* Out: True *)


Note that in the above I "hard-coded" the presence of $$a^3$$ specifically, and not any variable raised to the third power. If you wanted to apply your rule to another variable, then change the a^3 expression in those rules. If you wanted to apply it to any expression that contains a cube, independent of the name of the variable, then change a^3 to the pattern a_^3 in the left-hand sides of the expressions above.

• Hello! Please help me modify your code to transpose terms in such expressions: J.a^3 + J.(-P.a^3) /. x_Dot?(MemberQ[#, a^3] &) :> Transpose[x] J.a^3 + J.(-P.a^3) /.x_Dot?(MemberQ[#, (Dot[a___, a^3])] &) :> Transpose[x] Problem: a^3 in the corresponding term can be enclosed in brackets (moreover, the level of brackets can be arbitrary). It is necessary that the program works in the case of a deep level of brackets. Otherwise, only parts of the terms that are next to $a ^ 3$ and are separated from the rest of the term by brackets are transposed
– dtn
Sep 9, 2022 at 16:11
• @dtn That doesn't seem related to this question, so it would be best if you started a new question with your current problem. Sep 9, 2022 at 16:40
• Well, let's try! mathematica.stackexchange.com/questions/273219/…
– dtn
Sep 10, 2022 at 3:18