# Extract a term from a larger expression which satisfies some condition

I have an expression like:

$expr= \frac{1}{2}(A x^2y^2+ Bx^2Log[y]Cos[2\phi+\alpha] +C \frac{y^3}{x}Sin[\phi +\beta+\gamma]+DxCos[\phi])$

I have two problems as follows:

1.I want to extract those terms which contain $2\phi$ and $\phi$. i.e , I require output as:

$\phi term=\frac{1}{2}(C \frac{y^3}{x}Sin[\phi +\beta+\gamma]+DxCos[\phi])$

$2\phi term=\frac{1}{2}(Bx^2Log[y]Cos[2\phi+\alpha])$

$restterms=\frac{1}{2}(A x^2y^2)$

2.I would like to have the coefficient of the functions containing $2\phi$ and $\phi$.

$$\phi coeff=\frac{1}{2}(C \frac{y^3}{x}+Dx)$$ $$2\phi coeff=\frac{1}{2}(Bx^2Log[y])$$ I request solutions on how to do this.

One way might be

ClearAll[A0,B0,x,y,C0,D0,phi,beta,alpha,gamma]
expr=1/2(A0 x^2 y^2+B0 x^2 Log[y] Cos[2phi+alpha]+
C0 y^3/x Sin[phi+beta+gamma]+D0 x Cos[phi]);
expr = Expand[expr];


## Part 1

case1 = Cases[List@@expr,any1_. any2_[any3_.+ phi]:> any1 any2[any3+  phi]]


case2 = Cases[List@@expr,any1_. any2_[any3_.+ 2 phi]:> any1 any2[any3+ 2  phi]]


 rest =expr - (Plus @@ Flatten[{case1, case2}])


## Part 2

  Plus@@Cases[List@@expr,any1_. any2_[any3_.+  phi]:>any1 ]


  Plus@@Cases[List@@expr,any1_. any2_[any3_.+ 2 phi]:>any1 ]


• I just found out that "expr" cannot be a list in itself. I had to do the following in my code:  Expand[Flatten[expr]][[1]]  to get the answer. Dec 23, 2017 at 11:28

One way you could go about this would be to realise that your expression is just a list, with Parts that have Positions, just like any other:

exexpr = Expand[expr]

ϕpos = First /@ Position[exexpr, #] & /@ {ϕ, 2 ϕ};
ϕpospart = {Complement[Range@Length@exexpr, #1, #2],
Complement[#1, #2], #2} & @@ ϕpos;
Plus @@@ Map[exexpr[[#]] &, ϕpospart, {2}]

(* {1/2 A0 x^2 y^2,
1/2 D0 x Cos[ϕ] + (C0 y^3 Sin[β + γ + ϕ])/(2 x),
1/2 B0 x^2 Cos[α + 2 ϕ] Log[y]} *)


Giving you the rest, ϕ terms, and 2ϕ term.

For part 2:

ϕpos = (Position[exexpr, #] & /@ {ϕ, 2 ϕ})[[;; , ;; , {1, 2}]];
ϕpos2 = {Complement[#1, #2], #2} & @@ ϕpos;
Map[exexpr[[##]] & @@ # &, ϕpos2, {2}]
Plus @@@ (Drop[exexpr[[#1]], {#2}] & @@@ # & /@ ϕpos2)

(* {{Cos[ϕ], Sin[β + γ + ϕ]}, {Cos[α + 2 ϕ]}}

{(D0 x)/2 + (C0 y^3)/(2 x), 1/2 B0 x^2 Log[y]} *)


where the first output gives you the terms involving ϕ and 2ϕ, and the second gives you your desired coefficients.

I'm wouldn't go so far as to recommend doing it this way -- ignoring Mathematica's pattern matching functions when you're trying to match patterns seems ill-advised... Still, I'm kind of surprised this way worked at all.

• Will this work for larger and more random expressions? Dec 23, 2017 at 12:27
• It should do, or at least something very like it. It depends on how much/what kind of a generalization you're looking for. If you add a couple more test expressions I'll have a look (although it'll be tomorrow when I get a chance). Dec 23, 2017 at 12:45