Mathematica Asked on June 3, 2021
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?
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 *)
Correct answer by Bob Hanlon on June 3, 2021
You can use Variables
to obtain them without manually entering them:
x /. Verbatim[Plus][terms___] :> Plus @@ Pick[{terms}, UnitStep[2 - Length@*Variables /@ {terms}], 1]
Answered by Coolwater on June 3, 2021
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]]
Answered by bill s on June 3, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP