Search code examples
ampl

Use a variable as an index in AMPL


I need to use a variable to identify a value of a matrix. What I wanted to do is to define a variable like:

var a in A; # to say that the variable takes value from index A

and I wanted to use it as something like:

M1[a] >= 10;
M2[a] <= 100;

However AMPL complains:

variable in index expression

What can I point to an element of an array or matrix, using a variable? Thanks


Solution

  • AMPL doesn't allow variables in subscripts yet. However there is a way to emulate them. For example, M1[a] >= 10 can be emulated as follows:

       s.t. c: exists{i in A} (M1[i] >= 10 and i = a);
    

    This is not very efficient, but should work fine for small problems. Note that to solve a problem containing the above constraint (or variables in subscripts once they are added) requires a constraint programming solver such as ilogcp or gecode. See LOGIC AND CONSTRAINT PROGRAMMING EXTENSIONS for details.

    New version of ilogcp driver for AMPL supports the element constraint, for example:

    include cp.ampl;
    var x{i in 0..2} >= i integer;
    var y in 0..2 integer;
    minimize o: element({i in 0..2} x[i], y);
    option solver ilogcp;
    solve;
    

    where element({i in 0..2} x[i], y) is equivalent to x[y] and is translated into an IloElement constraint.