# Is there a way to prevent N from being applied to all parts of an expression

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

• Try N[expr] /. x[i_] :> x[Round[i]] – Marius Ladegård Meyer Aug 27 '16 at 15:45
• SetAttributes[x, NHoldAll]? There are also NHoldFirst, NHoldRest. – Michael E2 Aug 27 '16 at 16:00
• @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. – Mr.Wizard Aug 27 '16 at 17:50

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.

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] *)