# Filter out all terms not involving a given variable

Is it possible to filter out all terms in a sum that don't include a certain variable? Or equivalently keep only terms that involve a certain variable.

I would like to use such a function to experiment with the behavior of a sum with respect to a single variable (e.g., maximizing).

For example, if the input is $$(\cos(a)\sin(b)+b+\tan(b)c+a^2c, a)$$ I would like the output to be $$\cos(a)\sin(b)+a^2c.$$

I can't find an easy way to do this using DeleteCases or the like.

EDIT: Given confusion expressed about what I want I've changed the example and clarified the purpose.

• Okay... which variable was deleted here, exactly? I still see $a$ and $b$. – J. M.'s ennui Oct 8 '16 at 6:06
• Rephrasing, I only want to keep terms that include a given variable. – dysonsfrog Oct 8 '16 at 6:07

The example you show was not too clear. But I am assuming you have set of expressions, and you want to remove those that contain some symbol in them.

For example, given this set of expressions

ClearAll[a, b, x, y]
terms = {Cos[x] Sin[y],a Exp[y] +5 a,b Sin[x],c + y^2,Sin[x]+ 3 b +Cos[y]};


And the expression that contains, say b in it, is to be removed? In this case, you could first make a list of symbols in each expression, then use Pick to remove those that contain b as follows

doNotWant = b;  (*remove any expression with this symbol in it*)
lst = DeleteDuplicates[Cases[#, _Symbol, Infinity]] & /@ terms
Pick[terms, ! MemberQ[#, doNotWant] & /@ lst]


And if you want to remove expressions with say x in them

doNotWant = x;  (*remove any expression with this symbol in it*)
lst = DeleteDuplicates[Cases[#, _Symbol, Infinity]] & /@ terms
Pick[terms, ! MemberQ[#, doNotWant] & /@ lst]


And if you want to keep expressions with some symbol in it, then change the !MemberQ to MemberQ

keep = b;  (*keep expressions with this symbol in it*)
lst = DeleteDuplicates[Cases[#, _Symbol, Infinity]] & /@ terms
Pick[terms, MemberQ[#, keep] & /@ lst]


• The last version is exactly what I want (modulo converting sum to list, but I think I know how to do that). Thanks! – dysonsfrog Oct 9 '16 at 19:03
deleteWith[expr_, vars_] :=
DeleteCases[expr, term_ /; AllTrue[vars, ! FreeQ[term, #] &]]


Delete terms that contain, i.e. are not free of all the specified variables.

expr = Cos[a] Sin[b] Tan[c] + Cos[a] Sin[b] + b;

deleteWith[expr, {a, b, c}]


b + Cos[a] Sin[b]

deleteWith[expr, {a}]


b

• One comment: This form doesn't know how to overcome parentheses. Perhaps use Expand[expr] – Yair M May 25 '17 at 12:56