# StepMonitor variable replacement depends on presence of constraint in FindMinimum

Contrast the results of StepMonitor between the two calls to FindMinimum, which differ only in that the second contains a constraint on the argument to the objective function.

ClearAll[f, wrap, x];
f[x_] := (x)^2;
wrap = {x};
FindMinimum[{f[Sequence @@ wrap]}, x, StepMonitor :> Print["step to ", wrap]]
FindMinimum[{f[Sequence @@ wrap], x > 1}, x, StepMonitor :> Print["step to ", wrap]]

(*
step to {0.}
{0.,{x->0.}}
step to {x}
step to {x}
step to {x}
step to {x}
step to {x}
step to {x}
{1.,{x->1.}}
*)


The second version prints out {x} instead of the current guess of x. I need to be able to print out the current guess of the argument at each step without abandoning the constraint.

You might be wondering why I use wrap at all. The answer is that this is a minimal not working example of an issue I ran into for which the objective function is a function of several arguments, some of which are scalars with constraints, and some of which are variable length lists without constraints. I need to minimize the function over all of the arguments, and I can't hard code the arguments of the variable length lists into StepMonitor.

How could I alter my code so that StepMonitor will print out the current value of the arguments over which FindMinimum is searching without hard coding the variable names?

Use With to inject the value of wrap into your code (I also used f @@ wrap instead of your f[Sequence @@ wrap]):

f[x_] := x^2
With[{wrap = {x}},
FindMinimum[{f@@wrap}, x, StepMonitor:>Print["step to ", wrap]]
]


step to {0.}

{0., {x -> 0.}}

compared to:

With[{wrap = {x}},
FindMinimum[{f@@wrap, x>1}, x, StepMonitor:>Print["step to ", wrap]]
]


step to {2.}

step to {1.01}

step to {1.00986}

step to {1.00017}

step to {1.}

step to {1.}

{1., {x -> 1.}}

• Thank you. That worked in my more complicated setting as well. – FalafelPita Oct 9 '17 at 22:39