1
$\begingroup$

I have two functions f and g and a polynomial

 poly=p[1,1]+2*p[1,2]-3*p[1,3]-p[2,1]+p[2,2]-p[4,3]

and I want to transform the poly into

 f[1,1]+2*f[1,2]+3*g[1,3]+g[2,1]+f[2,2]+g[4,3]

Generally, I want to transform $$poly = \sum (-1)^{\tau_{i,j}} a_{ij}*p[i,j]$$ into $$\sum_{\tau_{i,j}=0} a_{ij}*f[i,j] + \sum_{\tau_{i,j}=1} a_{ij}*g[i,j]$$

What's the most elegant and efficient way?

$\endgroup$
1
  • $\begingroup$ @belisarius Thanks! One can define f and g himself, this is not the key point. I think the main obstacle is how to detect the sign of the coefficient. $\endgroup$ Dec 23, 2013 at 6:35

1 Answer 1

2
$\begingroup$

Not very general, as for symbolic coefficients you may not know the sign, but works in the case at hand:

poly=p[1,1]+2*p[1,2]-3*p[1,3]-p[2,1]+p[2,2]-p[4,3]
poly /. (Times[x_, a : p[__]] /; Negative[x] :> (-x g @@ a)) /. p :> f
(*
f[1, 1] + 2 f[1, 2] + f[2, 2] + 3 g[1, 3] + g[2, 1] + g[4, 3]
*)
$\endgroup$
4
  • $\begingroup$ Perfect! can you explain this code? $\endgroup$ Dec 23, 2013 at 9:11
  • $\begingroup$ +1 for using SetDelayed :D $\endgroup$
    – Mr.Wizard
    Dec 23, 2013 at 15:34
  • $\begingroup$ @Mr.Wizard Take a look at the edit history $\endgroup$ Dec 23, 2013 at 15:36
  • $\begingroup$ I already did. ;^) $\endgroup$
    – Mr.Wizard
    Dec 23, 2013 at 15:37

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.