0
$\begingroup$

I have a list with large expressions. I would like to find certain functions and their derivatives by searching the list. The search outcome should be the functions/derivatives found only, not the entire term or list element. For example, if a list element is the following:

3x1 F[x1, x2, x3] G[x1, x2] + x2 F^(1, 0, 1)[x1, x2, x3] + F[x1, x2, x3]

So if I search for F, I get

{F[x1, x2, x3], F^(1, 0, 1)[x1, x2, x3]}

and accordingly create a rule of association as follows:

{F[x1, x2, x3] -> g1, F^(1, 0, 1)[x1, x2, x3] -> g2}
$\endgroup$
  • $\begingroup$ Try this: DeleteDuplicates[Cases[3 x1 F[x1, x2, x3] G[x1, x2] + x2 Derivative[1, 0, 1][F][x1, x2, x3] + F[x1, x2, x3], F[__] | Derivative[__][F][__], ∞]] $\endgroup$ – J. M.'s discontentment Nov 15 '19 at 16:28
  • $\begingroup$ That seems to work great. Thanks. I have added another bit to the question if you could please help with that and post it as an answer. $\endgroup$ – Bran Nov 15 '19 at 16:41
  • $\begingroup$ For creating the rules, use Thread. $\endgroup$ – Rohit Namjoshi Nov 15 '19 at 17:25
1
$\begingroup$

As @J.M. pointed out in the comments, you can use Cases with Alternatives to get each appearance of either form F[__] or Derivative[__][F][__]. And together with Thread you can create a list of rules to be used as replacements.

termsearch[expr_, term_] := {#, Thread[# -> Array[g, Length@#]]}&@DeleteDuplicates@Cases[
  expr,
  (term[__] | Derivative[__][term][__]),
  ∞
]

termsearch[3 x1 F[x1, x2, x3] G[x1, x2] + x2 Derivative[1, 0, 1][F][x1, x2, x3] + F[x1, x2, x3], F]

{{F[x1, x2, x3], Derivative[1, 0, 1][F][x1, x2, x3]}, {F[x1, x2, x3] -> g[1], Derivative[1, 0, 1][F][x1, x2, x3] -> g[2]}}

Or a method (if you don't really care about the numbering of g or there are no duplicates) where you create the rules when Cases finds each appearance

termsearch2[expr_, term_] := {#[[;; , 1]], #} &@DeleteDuplicatesBy[
  Block[
    {k = 1}, 
    Cases[expr,  f : (term[__] | Derivative[__][term][__]) :> (f -> g[k++]), ∞]
  ],
  First
]
termsearch2[3 x1 F[x1, x2, x3] G[x1, x2] + x2 Derivative[1, 0, 1][F][x1, x2, x3] + F[x1, x2, x3], F]

{{F[x1, x2, x3], Derivative[1, 0, 1][F][x1, x2, x3]}, {F[x1, x2, x3] -> g[1], Derivative[1, 0, 1][F][x1, x2, x3] -> g[3]}}

Example

SetAttributes[p, Listable]
{a, b}.p[x, Range[0, 1]] + {c, d}.(p[x, Range[0, 1]] /. p -> p')
termsearch2[%, p]

a p[x, 0] + b p[x, 1] + c Derivative[1][p][x, 0] + d Derivative[1][p][x, 1]

{{p[x, 0], p[x, 1], Derivative[1][p][x, 0], Derivative[1][p][x, 1]}, {p[x, 0] -> g[1], p[x, 1] -> g[2], Derivative[1][p][x, 0] -> g[3], Derivative[1][p][x, 1] -> g[4]}}

| improve this answer | |
$\endgroup$

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.