# \[AMPL 24902\] optimizing index of summation in AMPL

**URL:** <https://discuss.ampl.com/t/ampl-24902-optimizing-index-of-summation-in-ampl/828>\
**Category:** Google Group Mirror\
**Created:** [November 23, 2023, 9:30pm UTC](https://discuss.ampl.com/t/ampl-24902-optimizing-index-of-summation-in-ampl/828 "2023-11-23T21:30:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![jclq](https://avatars.discourse-cdn.com/v4/letter/j/bb73d2/32.png) [@jclq](https://discuss.ampl.com/u/jclq)\
**Post date:** [November 23, 2023, 9:30pm UTC](https://discuss.ampl.com/t/ampl-24902-optimizing-index-of-summation-in-ampl/828/1 "2023-11-23T21:30:04Z")

</div>

Dear group,

I have an optimization problem where, I need maximize the summation index, as follows:

var **x** integer;  
var y {1… **x** } integer;

maximize **x** ;

subject to:

sum{i in 1… **x** }y[i] = a;

y[i] + y[j] \>= b;

and other constraints.

How could I write that model in AMPL.

I appreciate your help.

Regards

Julio

---

<div class="post-metadata">

**Author:** ![AMPL\_Google\_Group](https://avatars.discourse-cdn.com/v4/letter/a/9dc877/32.png) [@AMPL\_Google\_Group](https://discuss.ampl.com/u/AMPL_Google_Group)\
**Post date:** [November 25, 2023, 8:29pm UTC](https://discuss.ampl.com/t/ampl-24902-optimizing-index-of-summation-in-ampl/828/2 "2023-11-25T20:29:21Z")

</div>

AMPL does not accept indexing over {1…x} where x is a variable. This is because when AMPL sends the problem to the solver, it needs to tell the solver many variables are in the problem, and what coefficient each variable has in each constraint. If you have var y {1…x}, the number of y variables is not known until the solver determines the optimal value of x.

You’ll need to reformulate your problem so that AMPL and the solver can handle it. One way is to set a maximum possible value for x – call it xlim – then index y over 1…xlim, but add constraints that if i \> x, then y[i] must equal 0:

```auto
param a;
param xlim;

var x integer >= 0, <= xlim;
var y {1..xlim} integer >= 0;

maximize xval: x;

subject to ysum: sum {i in 1..xlim} y[i] = a;
subject to ysum_to_x {i in 1..xlim}: i > x ==> y[i] = 0;

```

The ==\> (“implies”) operator, used in constraint ysum\_to\_x, is recognized by CBC, COPT, GCG, Gurobi, HiGHS, Mosek, SCIP, and Xpress. (CPLEX will be added soon.) If you have any problem getting it to work, please reply with your model and data attached.

---

<div class="post-metadata">

**Author:** ![jclq](https://avatars.discourse-cdn.com/v4/letter/j/bb73d2/32.png) [@jclq](https://discuss.ampl.com/u/jclq)\
**Post date:** [November 27, 2023, 4:03pm UTC](https://discuss.ampl.com/t/ampl-24902-optimizing-index-of-summation-in-ampl/828/3 "2023-11-27T16:03:06Z")

</div>

Dear Robert, thanks for the suggestion, this is very helpful.

Regards.

Julio
