Recently, I have run into the problem where I need to collect the the sum of any number of gradients. I have defined a function grad[] to represent the gradient, and a typical question is like:
how to collect
grad[f]-grad[g]+grad[h]-grad[p] into
grad[f-g+h-p] Gradient can be collected this way since it is a linear operator. And so do other linear operators. I know I can write a binary rule and use ReplaceRepeated[] like:
grad[f]-grad[g]+grad[h]-grad[p]//.grad[a_]+grad[b_]:>grad[a+b] But the problem is, I am not satisfied with the algorithm efficiency of ReplaceRepeated[]. What I want is a patterned rule which does the trick with using ReplaceAll[] once rather than repeatedly.
Any idea how to achieve this?
Distribute[grad[f]-grad[g]+grad[h]-grad[p] /. a_ * grad[x_] :> grad[ a * x ], grad]solve your problem? $\endgroup$CollectGradient[]. However, what I want is a rule which can be used byReplaceAll[]once, your code seems not quite applicable in this case for the reasons: 1. The pattern of expression needs recognizing before the expression can be manipulated. 2. If your code is used as the r.h.s of the rule, there might appear nested replacement rules, I am not sure if that works. $\endgroup$