1
$\begingroup$

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 .

$\endgroup$
1
  • $\begingroup$ I tried exp/a[#]/;MemberQ[exp,a[#], Infinity]&Range[3]. But it did not work. $\endgroup$ Commented Mar 16, 2017 at 14:46

1 Answer 1

2
$\begingroup$
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}  *)
$\endgroup$
1
  • $\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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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