I have an expression of the form a1*x*b1^2 + a2*y*c1^2
I want to extract the x
and y
from the expressions. a_, b_, and c_
are the only types of variables that appear in the expression . Form of x
and y
are not known. Anyone know how? x
and y
are not necessarily numbers .
$\begingroup$
$\endgroup$
1
-
$\begingroup$ I tried exp/a[#]/;MemberQ[exp,a[#], Infinity]&Range[3]. But it did not work. $\endgroup$– Abhishek PalCommented Mar 16, 2017 at 14:46
Add a comment
|
1 Answer
$\begingroup$
$\endgroup$
1
f[expr_] := Module[
{vars = Variables[Level[expr, {-1}]]},
vars = Pick[vars,
Switch[#, "a" | "b" | "c", True, _,
False] & /@
(StringTake[ToString[#], 1] & /@ vars)];
((CoefficientList[expr, vars] // Flatten) /.
(0 :> Nothing))[[1]]]
expr1 = a1*x*b1^2 + a2*y*c1^2;
f /@ (List @@ expr1)
(* {x, y} *)
expr2 = a1*2*b1^2 + a2*y*c1^2;
f /@ (List @@ expr2)
(* {2, y} *)
Note that Mathematica may alter the form of an expression from what is manually entered
expr3 = a1*(y^2 + 2 x)*b1^2 + a2*y*c1^2
(* a2 c1^2 y + a1 b1^2 (2 x + y^2) *)
f /@ (List @@ expr3)
(* {y, 2 x + y^2} *)
-
$\begingroup$ thanks a lot. It took me while to look up the commands but I understand it now. Thanks a lot. $\endgroup$ Commented Mar 16, 2017 at 15:20