4
$\begingroup$

I have an expression of the type

expr = k*a + j*a + a*f + a*g + h

And I would like to set a=0 but ONLY if it's NOT multiplied by f or g. The result I'd want for the example would look like

expr = a*f + a*g + h

Is there a simple way to accomplish that? In general k and j may be unkown expressions, but I do know the form of f and g.

$\endgroup$
2
  • 3
    $\begingroup$ Maybe expr /. Times[a, b__] /; FreeQ[{b}, f | g] -> 0? $\endgroup$
    – Carl Woll
    Commented Oct 17, 2023 at 21:39
  • 1
    $\begingroup$ Perhaps, expr /. a Except[f | g] :> 0? But won'r work if there are other factors in each term. $\endgroup$
    – march
    Commented Oct 17, 2023 at 21:40

4 Answers 4

4
$\begingroup$
expr /. {p : (f | g)  a ___ :> p, a -> 0}
a f + a g + h
$\endgroup$
3
  • 1
    $\begingroup$ Thanks, this seems to work perfectly and is rather short. Just to understand what's going on, what this line does is: for any element "p" of the expression whose form is "f OR g" times "a" times "0 or more other elements" it replaces with itself (keeping it the same); it also sets "a" to zero. This works because /. uses the first rule in the list that is applicable to each element, and so it never tries to do a->0 to the "p" element since the first rule works. Is that correct? $\endgroup$ Commented Oct 18, 2023 at 20:29
  • $\begingroup$ @Bibliotebarbarian, that's exactly how/why ot works. $\endgroup$
    – kglr
    Commented Oct 18, 2023 at 20:33
  • $\begingroup$ Thanks, I'm trying to understand Mathematica patterns better $\endgroup$ Commented Oct 18, 2023 at 21:05
3
$\begingroup$

Something like this?

expr = k*a + j*a + a*f + a*g + h;
cl = CoefficientList[expr, a]
  (* {h, f + g + j + k} *)

{1, a} . 
  ReplacePart[cl, 
   2 -> (cl[[2]] /. (# -> 0 & /@ 
        Complement[cl[[2]] /. Plus -> List, {f, g}]))] // Expand

a f + a g + h

$\endgroup$
2
$\begingroup$
expr = k*a + j*a + a*f + a*g + h;

expr /. _[_, Alternatives @@ Cases[expr, Except[a | f | g], {2}]] :> 0

a f + a g + h

$\endgroup$
1
$\begingroup$

Using DeleteCases:

expr = k*a + j*a + a*f + a*g + h;

DeleteCases[expr, a*Except[f | g]]

a f + a g + h

Or using ReplaceAll:

expr /. a*Except[f | g] :> 0

a f + a g + h

$\endgroup$

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.