MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Help with NMinimize

  • To: mathgroup at
  • Subject: [mg82290] Re: Help with NMinimize
  • From: Szabolcs Horvát <szhorvat at>
  • Date: Wed, 17 Oct 2007 03:56:02 -0400 (EDT)
  • References: <ff1qmk$9eq$>

You should learn the basics of Mathematica before you start using it. 
There are many good tutorials in the documentation.  At least work 
through the one titled "First five minutes with Mathematica".

Flavio wrote:
> Hi everybody, I can't figure out how to solve this problem with
> NMinimize, which I want to use in order to test the Nelder and Mead
> algorithm with an externally evaluated function.
> I consider the following five argument function (of course this is not
> my actual minimization function):
> g[x1,x2,x3,x4,x5]:=Module[{xx1=x1,xx2=x2,xx3=x3,xx4=x4,xx5=x5},
> Export[ToString[xx1]<>".txt",xx1];
> Return[(xx1-1)^2+(xx2-1)^2-xx3^2+(xx4+1)^2+xx5^2];
> ]

The correct definition of this function would be

g[lst:{x1_, x2_, x3_, x4_, x5_} /; And @@ NumericQ /@ lst] :=
   ( Export[ToString[x1]<>".txt", x1];
     (x1-1)^2+(x2-1)^2-x3^2+(x4+1)^2+x5^2 )

The condition for the argument pattern is used to ensure that NMinimize 
won't evaluate g with symbolic arguments.  Now you can use:

NMinimize[{g[{x1,x2,x3,x4,x5}], constr},{x1,x2,x3,x4,x5}, Method-> 

> Now, if I compute
> g[1,2,3,4,5]
> I get the correct answer "14", and a file named "1.txt" is created,
> exactly as expected.
> But if I use the NMinimize command in this way:
> NMinimize[{g[x1,x2,x3,x4,x5],constr},{x1,x2,x3,x4,x5},Method-
>> {"NelderMead",RandomSeed->1},EvaluationMonitor:>Print["x1=",x1]]
> with these constraints:
> constr={x1^2<=4&&x2^2<=4&&x3^2<=4&&x4^2<=4&&x5^2<=4};
> The minimization is performed, but only a single file, named "x1.txt"
> is created.
> The x1 argument in the fuction seems to have the value "x1" rather
> than its effective value? Can somebody explain me which is the problem
> with my code, and how can I actually use the value inside the
> function?
> I need to use this value because the function g should be replaced by
> a function that creates a file with the arguments, evaluate a command,
> and then reads the values obtained by the external program.

Please read the tutorial tutorial/ExternalPrograms too.  You could use 
RunThrough[], or something simpler, like Get["!progname " <> 

> Thank you very much for your help.
> Flavio Cimolin


  • Prev by Date: Re: Is this normal for Limit?
  • Next by Date: Re: Integrate question
  • Previous by thread: Re: Help with NMinimize
  • Next by thread: Re: Help with NMinimize