list = {2 x1 + 3 x2 - 5 x1^2, 7 x2 - 3 x2^2, 2 x1 + 5 x2 - 9 x3, Sin[x1 + x4] + x5};
You can use FreeQ
with DeleteCases
, Cases
, Select
and Pick
as follows:
DeleteCases[_?(FreeQ[x1])]@list
Cases[_?(Not@*FreeQ[x1])]@list
Select[Not@*FreeQ[x1]]@list
Pick[list, Not @* FreeQ[x1] /@ list]
All methods above return
{2 x1 - 5 x1^2 + 3 x2, 2 x1 + 5 x2 - 9 x3, x5 + Sin[x1 + x4]}
To delete cases that does not contain x2
or x3
(to keep only those case that contain both x2
and x3
) use Alternatives (|)
in the pattern inside FreeQ
:
wanted = {x2, x3};
alt = Alternatives @@ wanted;
DeleteCases[_?(FreeQ[alt])]@list
Cases[_?(Not@*FreeQ[alt])]@list
Select[Not@*FreeQ[alt]]@list
Pick[list, Not @* FreeQ[alt] /@ list]
All four methods give
{2 x1 - 5 x1^2 + 3 x2, 7 x2 - 3 x2^2, 2 x1 + 5 x2 - 9 x3}
You can also use a combination of Level
and ContainsNone
or ContainsAny
as follows:
DeleteCases[_?(ContainsNone[Level[#, {-1}], wanted] &)]@list
Cases[_?(ContainsAny[Level[#, {-1}], wanted] &)]@list
Select[ContainsAny[Level[#, {-1}], wanted] &]@list
Pick[#, ContainsAny[Level[#, {-1}], wanted] & /@ #] &@list
to get
{2 x1 - 5 x1^2 + 3 x2, 7 x2 - 3 x2^2, 2 x1 + 5 x2 - 9 x3}
Note: Variables
"gives a list of all independent variables in a polynomial":
Variables /@ list
{{x1, x2}, {x2}, {x1, x2, x3}, {x5, Sin[x1 + x4]}}