0
$\begingroup$

Say I have the variable

x = a + a b + a b c + a b c d + ....

What is the easiest way to remove all terms with more than 2 variables? Up until now, I have used

x = a + a b + a b c + a b c d
coeffs = CoefficientRules[x, {a, b, c, d}];
selects = Select[coeffs, Total@(#[[1]]) <= 2 &];
x = FromCoefficientRules[selects, {a, b, c, d}]

Which works, but it requires me to manually enter each of the variable names. This becomes a tedious procedure when the number of variables is very high. Is there an easier way without specificing the variable names?

$\endgroup$
1
  • $\begingroup$ What if instead of a, b, c, ... you use indexed variables, e.g., a[1], a[2], a[3], ... ? $\endgroup$
    – yarchik
    Apr 15 at 8:32
1
$\begingroup$
x = a + a b + a b c + a b c d;

Select[x, Length[#] < 3 &]

(* a + a b *)

or

DeleteCases[x, _?(Length[#] > 2 &)]

(* a + a b *)

or

Total@Cases[x, _?(Length[#] < 3 &)]

(* a + a b *)
$\endgroup$
1
$\begingroup$

Replace your manual selection of variables with an automated selection:

x = a + a b + a b c + a b c d
coeffs = CoefficientRules[x, Variables[x]];
selects = Select[coeffs, Total@(#[[1]]) <= 2 &];
x = FromCoefficientRules[selects, Variables[x]]
$\endgroup$
0
$\begingroup$

You can use Variables to obtain them without manually entering them:

x /. Verbatim[Plus][terms___] :> Plus @@ Pick[{terms}, UnitStep[2 - Length@*Variables /@ {terms}], 1]
$\endgroup$
1
  • 1
    $\begingroup$ Your answer applied to x = a + a b + a b c + a b c d evaluates 0? $\endgroup$ Apr 15 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.