Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
1  
Try something like NMinimize[{a + 1, {Or @@ (a == # & /@ {-1, 0, 2}) && a > 0}}, a]? –  kguler Aug 15 at 21:37
1  
Or NMinimize[{a + 1, Times @@ ((a - #) &@{-1, 0, 2}) == 0}, a] –  belisarius Aug 15 at 21:44
    
Exactly what I need, thank you. –  Oxy Aug 15 at 21:59

1 Answer 1

Either 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]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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