5
$\begingroup$

Here is a simple example using ReplaceAll:

rvec[[2]] /. rvec -> {x, y}

I think Mathematica first tries to evaluate rvec[[2]], realising this is not a list, and only afterwards uses ReplaceAll. The warning output confirms this.

If instead of rvec[[2]] we have some complex expression (e.g. inversion of a matrix), Mathematica will to do it analytically first before making the substitution. This is not what I intend, I want to delay the evaluation of rvec[[2]] (or other more complex things in its place) until the ReplaceAll substitution has been done.

How can I tell Mathematica to substitute first, then evaluate?

$\endgroup$
3
  • 4
    $\begingroup$ With[{rvec = {x,y}}, rvec[[2]]]? $\endgroup$ Commented May 27, 2019 at 13:22
  • $\begingroup$ Thanks, this works. However, is it possible to keep my form (with a subsitution list) more or less intact? My rvec is really many expressions, and {x,y} a long substitution list. $\endgroup$ Commented May 27, 2019 at 14:08
  • $\begingroup$ I think it's best if you include a MWE where my trick above is inconvenient, and where a substitution really is required. Otherwise I'm not sure why you would want to do things your way (see What is the XY problem?). $\endgroup$ Commented May 27, 2019 at 15:00

3 Answers 3

4
$\begingroup$

You might be able to use Unevaluated:

Unevaluated[rvec[[2]]] /. rvec->{x,y}

y

$\endgroup$
4
$\begingroup$

You can also hold then release:

Hold[rvec[[2]]] /. rvec -> {x, y} // ReleaseHold

y

Pattern replacement works through hold.

$\endgroup$
1
$\begingroup$
(rvec /. rvec -> {x, y})[[2]]
$\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.