Ok, here is another approach:
ClearAll[findCoeff];
findCoeff[expr_, termToIsolate_] := Module[{findCoeffIn},
findCoeffIn[termToIsolate] = 1;
findCoeffIn[exprIn_Plus, OptionsPattern[]] := findCoeffIn /@ exprIn;
findCoeffIn[Times[lterms___, termToIsolate, rterms___]] :=
If[FreeQ[#, x], #, 0] &@Times[lterms, rterms];
findCoeffIn[exprIn : (Cos[_] | Sin[_] | Tan[_] | Cot[_]),
OptionsPattern[]] := findCoeffIn[TrigExpand[exprIn]];
findCoeffIn[_] := 0;
findCoeffIn[expr]
]
This seems to work on all the cases that I tried.
Use it like this:
In[1]:= findCoeff[Cos[2 x] + Cos[x + a] + 2, Cos[x]]
Out[1]= Cos[a]
In[2]:= findCoeff[2 Cos[x], Cos[x]]
Out[2]= 2
In[3]:= findCoeff[Cos[x + a] + Sin[2 x] + Cos[x], Cos[x]]
Out[3]= 1 + Cos[a]
In[4]:= findCoeff[Cos[2 x], Cos[2 x]]
Out[4]= 1
Something like findCoeff[Sin[2 x+a],Cos[2 x]]
will still not work as you want it to, though. One probably has to fiddle with FourierCosCoefficient
to do that.
In fact, I'm not even sure that the problem is well stated: consider for example Sin[2x]
. How should it expand? FourierCosCoefficient[Sin[2 x],x ,1]
gives the answer $8/3\pi$, while findCoeff[Sin[2 x],Cos[x]]
gives 0. While the former result answers a well defined question, what exactly are the rules according to which you want the latter result?
Old
Here is a slightly improved version of Kuba's idea:
Options[findCoeff] = {termToIsolate -> Cos[x],
independentVariable -> x};
findCoeff[expr_, OptionsPattern[]] := Total@Cases[
TrigExpand[expr],
cl___ OptionValue@termToIsolate cr___ :>
cl cr /; FreeQ[cl cr, OptionValue@independentVariable]
] /. {} -> 0
Examples:
In[1]:= findCoeff[Sin[2 x] + 2 Cos[x] + Cos[x + a]]
Out[1]= 2 + Cos[a]
In[2]:= findCoeff[Cos[y + x] + Sin[x], termToIsolate -> Cos[y],
independentVariable -> y]
Out[2]= Cos[x]
I'm not sure it would work on more complicated cases though.
{sin(x),cos(x)}
. This of course is due to the fundamental trig identity. A possible way around this would be to obtain coefficients in terms of both trig terms. $\endgroup$