# Using a variable as an index

How can we use a variable of an optimization problem as an index in another variable? I defined the first variable to be an integer, showing the time step number as an index of the second variable.

It sounds like a if-else constraint: if x ==0, y[0]<=something; if x ==1, y[1]<=somethingâ€¦ Using a big M method or something might work , see If-else statement

1 Like

Thanks very much for your note. I applied it, and it seemed it worked.
But I am facing another problem. After running the program, it shows me this error:

Error using cvx_sdpt3>solve
SDTP3 does not support integer variables.

Error in cvxprob/solve (line 435)
[ x, status, tprec, iters ] = shim.solve( At, b, c, cones, quiet, prec, solv.settings, eargs{:} );

Error in cvx_end (line 88)
solve( prob );

I used the following form of using integer variable in the optimization problem:

variable SP(N,1) integer;

Should I use another form produce an integer variable?
I think the cvx is using SDPT3 4.4 version.

You need to use a solver which supports integer variables. That effectively means Mosek or Gurobi. Technically, GLPK does (if the problem is linear other than the integer constraints, i.e., a MILP), but in practice I wouldnâ€™t count on GLPK working, correctly or at all, under CVX.

http://cvxr.com/cvx/doc/solver.html#supported-solvers

1 Like

Thanks very much, Mark. I installed Mosek, and it doesnâ€™t give me any error in this respect anymore.
However, I still get an error regarding my first question in this topic; I found a mistake that I made in it, and now it shows its real performance. I am not sure whether I followed the way mentioned by Jack correctly or not. The error is:

The following error occurred converting from cvxcnst to logical:
Disciplined convex programming error:
Constraints may not appear in if/then statements.

The error refers to the line representing like:

``````            if m(i) == L+j
``````

The whole current section representing my first question is like:

for i=1:N
m(i) >= L(i);
m(i) <= U(i);
P=U(i)-L(i);
for j=1:P
if m(i) == L+j
for k=1:y(i)
T(i, (L+j)+k-1) == b;
end
end
end
end

a is a constant integer.
N is a constant scalar.
L, U, and y are constant vectors.
m is a variable vector.
T is a variable matrix.

You canâ€™t use if on a CVX expression. You need to use Big M to implement logic constraints. Thatâ€™s what @jackfsuia was suggesting.

1 Like

This may also be helpful, even if you use CVX (except CVX doesnâ€™t have `implies`).

1 Like

I followed the instructions regarding employing the Big-M method from those sources you mentioned. I applied the method on the program, and it seems it is working now.
I really appreciate your help and consideration Mark and Jack.