# Why can't I define a function using the Minimization function in Mathematica?

Suppose I define a function in this way:

function[x_,y_]=Minimize[E^(x^2 + y^2 + z^2 + w^2 + x*y + x*z + x*w + y*z + y*w + z*w), {z,w}]

The output in Mathematica will give me the minimal value of the expression and the values for z and w that minimize the expression. If I want to extract just the minimum value for this output, I can call function[1,1][[1]] and this will return the minimal value. Now, suppose I want to define a new function that returns this minimal value, i.e., define:

function2[x_,y_] = function[x,y][[1]]

If I call function2[1,1], I don't get the minimal value that was output when calling function[1,1][[1]], but rather an expression involving the variables z and w. Is there any way to fix this and accomplish my goal of defining a new function that extracts the minimal value from Minimize?

• (1) Consider using ?NumericQ on the parameters x and y. (2) Define function2 with := instead of =. Feb 15 at 1:07
• I was searching for the link. I just added it to my comment. The formal names for := and = are SetDelayed and Set Feb 15 at 1:09

f[x_?NumericQ, y_?NumericQ] :=
NMinimize[
E^(x^2 + y^2 + z^2 + w^2 + x*y + x*z + x*w + y*z + y*w + z*w), {z,
w}][[1]];
f[1,1]

• The comment have solve the question :) Feb 15 at 1:28

The problem is that your definitions use Set (=) rather than SetDelayed (:=) in their definitions. = evaluates its right hand side on the spot. You get away with that for function because Minimize can't do the job for unknown x and y, so evaluation does nothing. But in function2, Part extracts the first part of the Minimize expression, and that becomes the definition. It works if you do:

function2[x_, y_] := function[x, y][[1]]


because := delays evaluation until you "call" function2. I'd recommend using := in the definition of function also, because the fact that your definition works is a bit of an accident.

• @LunarCrater just as an aside/fyi, for SE sites like this, it is often better to let your questions collect answers over some 24 hours or so before accepting an answer so as to get the best answer possible (& get more answers, too!) Feb 15 at 4:58
• @LunarCrater No problem, I do this for fun, not for points. Feb 15 at 15:19
• @LunarCrater See cvgmt's answer and learn to use ?NumericQ. Feb 15 at 15:27