1
$\begingroup$

Given the following expression

expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];

I would like to achieve the following output:

output = x Cos[y]^2 + Sin[x^2 z Cos[y]^2]

I tried it with case

Cases[expr, t : _Cos :> t^2, All]

but the result is not what I expected.

$\endgroup$
2
  • $\begingroup$ Do I understand correctly: You want to get all terms that contain Cos somewhere in them, and then replace each Cos[...] with Cos[...]^2? $\endgroup$
    – Domen
    Sep 21, 2023 at 11:09
  • $\begingroup$ @Domen That is precisely right. But I wanted to do that by matching patterns for the Head. $\endgroup$
    – Harken
    Sep 21, 2023 at 12:02

1 Answer 1

0
$\begingroup$

May be you need two patterns?

ClearAll["Global`*"]
expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];
pat = {h_.*f_[g_.*(t : _Cos)] :> h*f[g*t^2], g_.*(t : _Cos) :> g*t^2};
Plus @@ Flatten[Cases[expr, #] & /@ pat]

Mathematica graphics

Alternatives does not work, since Cases matches on first Alternative found, not all of them.

Here is another way using replace, which I think is simpler

ClearAll["Global`*"]
expr = x Cos[y] + x^(2 y) + x y + Sin[x^2 z Cos[y]];
expr = DeleteCases[expr, x_ /; FreeQ[x, _Cos]];
expr /. Cos[t_] :> Cos[t^2]

Mathematica graphics

$\endgroup$

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.