Skip to main content

simplifying expressions - 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.



Answer



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]};

Mathematica graphics


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]


Mathematica graphics


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]

Mathematica graphics


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]

Mathematica graphics


Comments