2
$\begingroup$

I want to isolate positive and negative terms in this algebraic expression, for example. I have looked at the FullForm and tried many functions like Gatherby, Split etc. but they work on lists and the -1 is imbedded in a function Rational. From the Stack Exchange questions, I found that the best result is with:

expression/._?Positive->0

expression/._?Negative->0

But it adds few terms and misses others... Any quick help? The expression is:

expression = (a Nb^2)/2 + c^2 f$K^2 my$i$Re mz$i$Im Cos[θ]^2 + 
1/2 I bN$f c f$K my$i$Im Cos[θ] Sin[θ] - 
1/2 I bN$i c f$K my$i$Im Cos[θ] Sin[θ] + 
1/2 bN$f c f$K my$i$Re Cos[θ] Sin[θ] + 
1/2 bN$i c f$K my$i$Re Cos[θ] Sin[θ] + 
c^2 f$K^2 mx$i$Re mz$i$Im Cos[θ] Sin[θ] + 
1/2 I bN$f c f$K mx$i$Im Sin[θ]^2 - 
1/2 I bN$i c f$K mx$i$Im Sin[θ]^2 + 
1/2 bN$f c f$K mx$i$Re Sin[θ]^2 + 
1/2 bN$i c f$K mx$i$Re Sin[θ]^2 + 
1/2 c^2 f$K^2 my$i$Im^2 Cos[θ]^2 Sin[θ]^2 + 
1/2 c^2 f$K^2 my$i$Re^2 Cos[θ]^2 Sin[θ]^2 + 
c^2 f$K^2 mx$i$Im my$i$Im Cos[θ] Sin[θ]^3 + 
c^2 f$K^2 mx$i$Re my$i$Re Cos[θ] Sin[θ]^3 + 
1/2 c^2 f$K^2 mx$i$Im^2 Sin[θ]^4 + 
1/2 c^2 f$K^2 mx$i$Re^2 Sin[θ]^4
$\endgroup$
3
$\begingroup$
expression /. _?Internal`SyntacticNegativeQ :> 0

(a Nb^2)/2 + c^2 f$K^2 my$i$Re mz$i$Im Cos[θ]^2 + 
  1/2 I bN$f c f$K my$i$Im Cos[θ] Sin[θ] + 
  1/2 bN$f c f$K my$i$Re Cos[θ] Sin[θ] + 
  1/2 bN$i c f$K my$i$Re Cos[θ] Sin[θ] + 
  c^2 f$K^2 mx$i$Re mz$i$Im Cos[θ] Sin[θ] + 
  1/2 I bN$f c f$K mx$i$Im Sin[θ]^2 + 
  1/2 bN$f c f$K mx$i$Re Sin[θ]^2 + 
  1/2 bN$i c f$K mx$i$Re Sin[θ]^2 + 
  1/2 c^2 f$K^2 my$i$Im^2 Cos[θ]^2 Sin[θ]^2 + 
  1/2 c^2 f$K^2 my$i$Re^2 Cos[θ]^2 Sin[θ]^2 + 
  c^2 f$K^2 mx$i$Im my$i$Im Cos[θ] Sin[θ]^3 + 
  c^2 f$K^2 mx$i$Re my$i$Re Cos[θ] Sin[θ]^3 + 
  1/2 c^2 f$K^2 mx$i$Im^2 Sin[θ]^4 + 
  1/2 c^2 f$K^2 mx$i$Re^2 Sin[θ]^4

To replace the terms with a positive sign with 0:

Replace[expression , Except[_?Internal`SyntacticNegativeQ] :> 0, 1]

 -(1/2) I bN$i c f$K my$i$Im Cos[θ] Sin[θ] - 1/2 I bN$i c f$K mx$i$Im Sin[θ]^2
$\endgroup$
2
  • $\begingroup$ Thank you very much! Somehow, these type of operations should not be Internal but more user friendly. But I won't complain, it works! $\endgroup$ – Gwanguy Oct 19 '18 at 21:23
  • $\begingroup$ I had trouble with the first expression (for the positive) but the command: Replace[expression, _?Internal`SyntacticNegativeQ :> 0, 1] works! $\endgroup$ – Gwanguy Oct 19 '18 at 21:33

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.