Skip to main content

pattern matching - Select certain terms in an expression


I would like to have a function to select terms containing q[i] terms in expressions, for example, for an expression


a q[i]+b +c q[j]+d

I would like the function to return


a q[i]+c q[j]

as result. Also at the same time, for a bare


q[i]


the same function would return


q[i]

How to realize such function? Thanks



Answer



A pattern-based approach.


fn[x_. y_q + z_.] := x y + fn[z]
_fn = 0;

a q[i] + b + c q[j] + d // fn


q[i] // fn


a q[i] + c q[j]

q[i]

Comments