1
$\begingroup$

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?

$\endgroup$
2
  • 1
    $\begingroup$ (1) Consider using ?NumericQ on the parameters x and y. (2) Define function2 with := instead of =. $\endgroup$
    – Michael E2
    Feb 15 at 1:07
  • 1
    $\begingroup$ I was searching for the link. I just added it to my comment. The formal names for := and = are SetDelayed and Set $\endgroup$
    – Michael E2
    Feb 15 at 1:09
3
$\begingroup$
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]
$\endgroup$
1
  • 1
    $\begingroup$ The comment have solve the question :) $\endgroup$
    – cvgmt
    Feb 15 at 1:28
2
$\begingroup$

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.

$\endgroup$
3
  • $\begingroup$ @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!) $\endgroup$ Feb 15 at 4:58
  • 1
    $\begingroup$ @LunarCrater No problem, I do this for fun, not for points. $\endgroup$
    – John Doty
    Feb 15 at 15:19
  • $\begingroup$ @LunarCrater See cvgmt's answer and learn to use ?NumericQ. $\endgroup$
    – John Doty
    Feb 15 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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