[AMPL 24813] Rejecting declaration because it uses loop dummy n_val

Hi, I want to write a code that uses for loop. I have an error: “Rejecting declaration because it uses loop dummy n_val.
context: var temp := >>> n_val; <<<”

To be honest I’ve tried several solutions and non of them worked fine. This is my first program in AMPL ever, thans in advance for any help.


#choose solver

option solver cplex;

option log_file “C:\Users\asia-\Desktop\BI 2\Games and decisions in management\solution1 3a.txt”;

#start new model (clear AMPL memory)


#input data

set n := 1…10; #number of items

for {n_val in n} {

#decision variables

var temp := n_val;

var x{1…temp} binary;

#objective function

maximize value:sum{i in 1…temp} i*x[i];


subject to

knapsack: sum{i in 1…temp} i*x[i]<=n_val/2;


#provide data

#solve the model and display results


display temp, value > ‘C:\Users\asia-\Desktop\BI 2\Games and decisions in management\results1_3.txt’;



Model definition statements (var, maximize, subject to) have to be executed only once, so they should not be placed inside a “for” loop. Instead, define the model before the loop, with a parameter n_val to specify the numbers of variables and constraints:

param n_val;

var x {1..n_val} binary;

maximize value: 
   sum {i in 1..n_val} i*x[i];

subject to knapsack:
   sum {i in 1..n_val} i*x[i] <= n_val/2;

Then execute a loop that sets n_val to 1, 2, 3, . . . , 10 and solves for each n_val:

option solver cplex;

for {i in 1..10} {
   let n_val := i;
   display n_val, value

Each time that the loop changes n_val, AMPL automatically updates the model.