11

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

BioPhysicist
  • 1,124
  • 5
  • 16

2 Answers2

9

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.

Michael E2
  • 235,386
  • 17
  • 334
  • 747
0

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] *)
mikado
  • 16,741
  • 2
  • 20
  • 54