## sorting values in a variable

Problems with syntax of GAMS
dunyayigezerken
User Posts: 7
Joined: 6 months ago

### sorting values in a variable

Hello,

I have a problem for my PhD thesis in GAMS. The problem is I have a variable (not parameter) c(j) and I calculated it with my function. And after 5 indices the 6th indice value must be made by comparing the rest of 5 c(j) values, it is a condition. However, it has to be done by sorting as I guess. For example first five c(j) are 35, 48, 12, 45, 64 and 6th will be constrained by using the smallest of the rest of all. In that example, obviously it is 12, however I know it but the model doesnt know it, so I have to sort the c(j) in ascending, so in this way I hope I can compare by (k-5) which compares c(6) and c(1) then c(7) and c(2) etc. Is there any idea how I can do it.

Thanks in advance. bussieck
Moderator Posts: 285
Joined: 2 years ago

### Re: sorting values in a variable

From how you describe it you seem to want this as part of an optimization model. In traditional optimization models "sorting" is not possible. You can try to reformulate this using traditional optimization techniques:
1. make a new variable c5min(j) with "c5min(j) = min(c(j-5),c(j-4),c(j-3),c(j-2),c(j-1))"
2. add constraint c(j) = c5min(j)
You can write the first constraint like this in GAMS but you end up with a dnlp. Some solvers (e.g. Lindo) reformulate this automatically into linear constraints with discrete helper variables. You find plenty of places where this reformulation is described (e.g. https://orinanobworld.blogspot.com/2011 ... n-mip.html) in case you want to do it yourself and use your favorite MIP solver.

I am not sure if this is really what you want. Such a c sequence will be "boring" because all values after j=5 will be fixed at the smallest value of c(1)-c(5).

-Michael

dunyayigezerken
User Posts: 7
Joined: 6 months ago

### Re: sorting values in a variable

Actually, that is what I want to do below.

a(j) c(j)
1 60 72
2 64 95
3 66 38
4 68 65
5 ???

the last indice for a(j) must be under the value of c(j) - 5, it may be good for all of them. but, there is also a constraint for a(j) like max or min value for a(j) as determined in parameters so not all c(j) can provide, model has to choose. I want to take smallest c(j) then I will compare it regarding the max and min value for a(j), if it is correct, I will count it in a summation of binary variable, so if there is correct at least 1 time it will be 38-5=33 for value of a(5) then it is not important that all c(j) provides the constraint or not because at least 1 is enough for that.

bussieck
Moderator Posts: 285
Joined: 2 years ago

### Re: sorting values in a variable

I am not sure I follow completely, but I think with the pointers I send earlier your should have enough information to implement this.

-Michael

dunyayigezerken
User Posts: 7
Joined: 6 months ago

### Re: sorting values in a variable

Thank you very much again.