Variables with Duplicate Names Disallowed
If you use two different variables that have the same name, then optimization expressions, constraints, or problems can throw an error. This error is troublesome when you create a variable, then create an expression using that variable, then recreate the variable. Suppose that you create the following variable and constraint expression:
x = optimvar('x',10,2); cons = sum(x,2) == 1;
At this point, you realize that you intended to create integer variables. So you recreate the variable, changing its type.
x = optimvar('x',10,2,'Type','integer');
Create an objective and problem.
obj = sum(x*[2;3]); prob = optimproblem('Objective',obj);
Now try to put the constraint into the problem.
prob.Constraints = cons
At this point, you get an error message stating that
OptimizationVariables appearing in the same problem must have
distinct "Name" properties. The issue is that when
you recreated the
x variable, it is a new variable, unrelated to the
You can correct this issue in two ways.
Create a new constraint expression using the current
cons = sum(x,2) == 1; prob.Constraints = cons;
Retrieve the original
xvariable by creating a problem using the old expression. Update the retrieved variable to have the correct
Typeproperty. Use the retrieved variable for the problem and objective.
oprob = optimproblem('Constraints',cons); x = oprob.Variables.x; x.Type = 'integer'; oprob.Objective = sum(x*[2;3]);
This method can be useful if you have created more expressions using the old variable than expressions using the new variable.