2
$\begingroup$

Let's say I have aset = {-1, 0, 2}. I would like to create a variable Var that takes values from that set, i.e. var = -1 or var = 0 or var = 2. What I'm trying to do is using the variable in NMinimize as a constraint. A simple example could be as follow:

NMinimize[{a + 1, var == -1 || var == 0 || var == 2, a > 0}, a]

The result is, obviously:

{1., {a -> 0.}}

But if the set is much larger I can't write down constraints for each element. Is there a more efficient way to do this?

Edit

Both answers work (see comments). However, if I change the code a bit,

set = {b^2, b^2 + 1, b^2 - 1};
NMinimize[{a + 1, Or @@ (a == # & /@ set)}, {a, b}]

gives

{-7.45058*10^-9, {a -> -1., b -> -7.43726*10^-9}}`

while

NMinimize[{a + 1, Times @@ ((a - #)& @ set) == 0}, {a, b}] 

gives

{-3.53148*10^-9, {a -> -1., b -> -7.29659*10^-9}}

Both results are satisfactorily correct. However I notice that the second result is a little bit more accurate.

$\endgroup$
  • 1
    $\begingroup$ Try something like NMinimize[{a + 1, {Or @@ (a == # & /@ {-1, 0, 2}) && a > 0}}, a]? $\endgroup$ – kglr Aug 15 '14 at 21:37
  • 1
    $\begingroup$ Or NMinimize[{a + 1, Times @@ ((a - #) &@{-1, 0, 2}) == 0}, a] $\endgroup$ – Dr. belisarius Aug 15 '14 at 21:44
  • $\begingroup$ Exactly what I need, thank you. $\endgroup$ – Oxy Aug 15 '14 at 21:59
5
$\begingroup$

Any of the following, taken from the comments, will work.

kguler's answer.

NMinimize[{a + 1, {Or @@ (a == #& /@ {-1, 0, 2}) && a > 0}}, a]

belisarius' answer.

NMinimize[{a + 1, Times @@ ((a - #)& @ {-1, 0, 2}) == 0}, a]

Another possibility:

NMinimize[{a + 1, Or @@ Thread[a == {-1, 0, 2}] && a > 0}, a]
$\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.