开发者

Generating constraints from a list of variables for use in NMaximize

I have an issue concerning constraints which should be generated 开发者_如何学运维dynamically from a list of variables.

Suppose I have an expression which is contained in variable R which itself has a varying number of variables in it, like x[1]*5+x[3]*x[2]. If I knew the number upfront I would just use NMaximize[{R, 1 > x[1] > -1 && 1 > x[2] > -1 && 1 > x[3] > -1}, f] where f is a list of the variables x constructed by f = Array[x,n], n being the number of variables I use.

As others do not seem to have similar problems I assume that this is not the way in which such issues are normally addressed in mathematica... However if there is a way to tackle this problem easily I would be glad to hear about it (otherwise I would also be glad to hear about a way to bypass that whole thing).

Thanks in advance!


Suppose this is your expression:

In[1]:= r = x[1]*5+x[3]*x[2];

It is relatively easy to extract a list of variables if you know their base symbol:

In[5]:= vars = Union@Cases[r,x[_],Infinity]
Out[5]= {x[1],x[2],x[3]}

Now you can call NMaximize with dynamically generated constraints:

In[7]:= NMaximize[{r,And@@Map[Greater[1,#,-1]&,vars]},vars]
Out[7]= {6.,{x[1]->1.,x[2]->-1.,x[3]->-1.}}

The code And@@Map[Greater[1,#,-1]&,vars] specifically answers your question, generating the constraints. You can execute it stand-alone to see them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜