11
$\begingroup$

Is there a more compact way to represent these constraints:

NMaximize[{a+b+c,a <= 5 && b <= 5 && c <= 5}, {a,b,c}]

like for x in {a,b,c}, x <= 5 or something.

$\endgroup$
0

4 Answers 4

14
$\begingroup$

I personally like to use Thread for such things (bounds are e.g. easy to adjust), like:

NMaximize[{a + b + c, Thread[{a, b, c} <= {5, 6, 7}]}, {a, b, c}]

If it is all the same bound, we can directly write (as in Artes' comment below):

NMaximize[{a + b + c, Thread[{a, b, c} <= 5]}, {a, b, c}]

I think the syntax should be clear - see also Docu Center for a very similar example (on Thread)

Also see Artes' comment below for further ideas based on the (exemplary) function you provide.

$\endgroup$
3
  • 3
    $\begingroup$ NMaximize[{a + b + c, Thread[{a, b, c} <= 5]}, {a, b, c}] or simply NMaximize[{a + b + c, Thread[# <= 5]}, #] &@{a, b, c}, or NMaximize[{Plus @@ #, Thread[# <= 5]}, #] &@{a, b, c}. $\endgroup$
    – Artes
    Commented Aug 19, 2013 at 11:29
  • $\begingroup$ Thanks @Artes, I added that to the list and made clear that my previous answer was gear towards different bounds $\endgroup$ Commented Aug 19, 2013 at 11:31
  • $\begingroup$ Thanks. Thread[] seems similar to Haskell's generalized map "fmap" (Functor). $\endgroup$ Commented Aug 19, 2013 at 12:56
7
$\begingroup$

If you do these things a lot you may consider building your own syntax to be able to write constraints in a more concise manner, e.g.:

constrAnd[list_, func_] := And @@ (func /@ list)
lt[list_,n_] := constrAnd[{a, b, c}, # <= n &]
lt[{a, b, c},5]

a <= 5 && b <= 5 && c <= 5

So that you may now write

NMaximize[{a + b + c, lt[{a, b, c}, 5]}, {a, b, c}]

This function is logically equivalent to the example in the OP, "for x in ...".

$\endgroup$
6
$\begingroup$

What about this (because NMinimize also accepts a list of boundary conditions):

NMaximize[{a + b + c, # <= 5 & /@ {a, b, c}}, {a, b, c}]

or (if you are after the very same expression)

NMaximize[{a + b + c, And @@ (# <= 5 & /@ {a, b, c})}, {a, b, c}]

Both are obviously not more compact as such, but very easily adapted to larger number of parameters.

$\endgroup$
0
$\begingroup$

If all elements of your list share the same upper bound, you can write Max[{a,b,c}]<5

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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