12
$\begingroup$

I am working on modifying a mathematical expression and need some assistance. I have the following equation:

-27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

I aim to replace occurrences of f with f[n], but I want to apply this transformation selectively. Specifically, I aim to replace f only where it does not serve as a function head. That means I want to transform standalone instances of f into f[n] without altering f when it's followed by square brackets and arguments (like f[1 + n], f[2 + n], etc.).

Is there a method or function in Mathematica to help me achieve this selective replacement?

$\endgroup$

4 Answers 4

8
$\begingroup$
expr = -27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n;

p = Position[expr, f, Heads -> False]

{{1, 1, 2}}

MapAt[f[n] &, expr, p]

-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

$\endgroup$
12
$\begingroup$

This trick is often useful with ReplaceAll: if you want some things to remain unaffected, you add a trivial replacement rule for that case before the replacement rule you really want

-27  f + 27  f[1 + n] - 9  f[2 + n] + f[3 + n] == 1 + 3  n /. {
  expr : _f :> expr,
  f -> f[n]
}

-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

$\endgroup$
2
  • $\begingroup$ What does _f do here? $\endgroup$ Commented Feb 20 at 9:48
  • $\begingroup$ @faceclean _f is a pattern that matches expressions like f[1 + n] where f is the head. $\endgroup$ Commented Feb 20 at 9:56
5
$\begingroup$
expr = -27 f + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

expr /. f[a__] :> g[a] /. f -> f[n] /. g[a__] :> f[a]

Result:

-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n

$\endgroup$
1
$\begingroup$
expr = -27  f + 27  f[1 + n] - 9  f[2 + n] + f[3 + n] == 1 + 3  n;

Another way using Cases:

vars = Union@Cases[#, s1_@s2_ | s3_Symbol, Depth@#] &@expr;

rules = # -> If[# === f, #[n], #] & /@ # &@vars;

expr /. rules

(*-27 f[n] + 27 f[1 + n] - 9 f[2 + n] + f[3 + n] == 1 + 3 n*)
$\endgroup$

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.