# How to transform the polynomial in this way?

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?

-
@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. – Eden Harder Dec 23 '13 at 6:35

## 1 Answer

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]
*)

-
Perfect! can you explain this code? – Eden Harder Dec 23 '13 at 9:11
+1 for using SetDelayed :D – Mr.Wizard Dec 23 '13 at 15:34
@Mr.Wizard Take a look at the edit history – belisarius is forth Dec 23 '13 at 15:36
I already did. ;^) – Mr.Wizard Dec 23 '13 at 15:37