1
$\begingroup$

I can only write like this:

NMinimize[
  {GoalFunction[graph, {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12}], 
  cons[graph, {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12}, 2500],
  x1 > 0, x2 > 0, x3 > 0, x4 > 0, x5 > 0, x6 > 0, x7 > 0, 
  x8 > 0, x9 > 0, x10 > 0, x11 > 0, x12 > 0},
  {x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12}
]

But when I have thousands of variables, how to use it?

$\endgroup$
  • 1
    $\begingroup$ Are you asking how to automate the input of variables without having to type each one? $\endgroup$ – Marius Ladegård Meyer Sep 10 '16 at 8:05
5
$\begingroup$

If you can avoid it: You don't. Use FindMinimum with a good starting point, if you can. NMinimize usually gets horribly slow when the number of variables increases.

Regarding syntax, you can a simple trick (works for FindMinimum and NMinimize): Declare an array of variables like this:

xs = Array[x, 12]

Now xs contains 12 separate variables:

{x[1], x[2], x[3], x[4], x[5], x[6], x[7], x[8], x[9], x[10], x[11], x[12]}

and you can use xs instead of writing the same 12 variables again and again:

FindMinimum[
  {GoalFunction[graph, xs], cons[graph, xs, 2500], Thread[xs > 0]},
  xs]

This works well for small to medium sized problems (thousands of variables).

$\endgroup$
1
$\begingroup$

I would try to use:

Module[{x = x, n = 12, vars},
 vars = ToExpression[ToString[x] <> ToString[#]] & /@ Range[n];
NMinimize[
 Flatten@{GoalFunction[graph, vars], cons[graph, vars, 2500], 
  Thread[vars > 0]}, vars]
]
$\endgroup$

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.