I am trying to do the the following: precomputing an expression and then making a function out of it. It has to be delayed evalution, because some of the parameters are only known when the function is called. A simplified example (the real expression is much more convoluted), is:


What we get:

FindMinimum::nrlnum: The function value {1.41421,1.41421 y} is not a list of real numbers with dimensions {2} at {x} = {1.}.
FindMinimum[expression, {x, 1}]

What I expected is


If I remove delayed evaluation, it tries to run FindMinimum immediately and fails. Usually, Evaluate works, but here, it does not. If I both use immediate assignment = and Evaluate, it also tries minimizing before y is ready.

There numerous threads on this SE that almost work, but not for FindMinimum. I tried With, Block and others. If I missed the true answer, please point me to it.

It seems this type of converting expressions into functions should be straight forward. I usually resort to copy-pasting expressions into functions, but this is cumbersome and may lead to many mistakes when expressions are recomputed and the change must be propagated downstream.

  • $\begingroup$ @xzczd Thank you, this indeed helped, I didn't expect this problem to have such an obscure solution. Better remember this one for the future, it happens a lot also with Manipulate, Plot and others. $\endgroup$ – orion Nov 11 '19 at 14:32
(test[y_] := FindMinimum[#, {x, 1}]) &@expr

Not the answer you're looking for? Browse other questions tagged or ask your own question.