9
$\begingroup$

For example. If I have

N[x[1]]

how do I prevent it from returning

x[1.]

since I want to keep the variable as x[1]. I am using indexed variables like this in NonlinearModelFit where the form has N[expression involving indexed variables], but since the variable becomes x[1.] it no longer matches the parameter x[1] I use in NonlinearModelFit

$\endgroup$
  • $\begingroup$ Try N[expr] /. x[i_] :> x[Round[i]] $\endgroup$ – Marius Ladegård Meyer Aug 27 '16 at 15:45
  • 7
    $\begingroup$ SetAttributes[x, NHoldAll]? There are also NHoldFirst, NHoldRest. $\endgroup$ – Michael E2 Aug 27 '16 at 16:00
  • 1
    $\begingroup$ @Michael I think that is worthy of an answer. If one doesn't already know about these attributes they are not necessarily easy to find. $\endgroup$ – Mr.Wizard Aug 27 '16 at 17:50
8
$\begingroup$

You can protect arguments inside brackets from N with the family of attributes, NHoldAll, NHoldFirst, and NHoldRest.

For an indexed variable such as x[1], x[2], etc., either

SetAttributes[x, NHoldAll]    (* what I would normally use *)

or

SetAttributes[x, NHoldFirst]  (* protects only the first argument *)

would keep the index from being numericized by N:

N[x[1]]
(*  x[1]  *)

Attributes of x can be cleared with ClearAttributes[x, <attribute>] or ClearAll[x], but NOT with Clear[x].

Built-in functions that require some or all arguments to be an integer (e.g. Take, Part), an exact number (e.g., AlgebraicNumber), or simply protected from being changed by N (e.g. Subscript) have one of these attributes.

$\endgroup$
0
$\begingroup$

One approach is to use a replacement rule matching the items you would like to convert. Prior terms items in the replacement list can "protect" terms you would like to leave untouched. E.g.

π x[1] + Sqrt[2^x[3]] + s[5] /. {u : _x | _s -> u, v_?NumericQ :> N[v]}
(* (2.^x[3])^0.5 + s[5] + 3.14159 x[1] *)
$\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.