MATLAB: Unique variable values in ga

constrained optimizationgaoptimization

I am trying to write a code to optimise a stack of materials, based on certain parameters.
Currently I have an integer constrained ga optimisation, basically evaluating the objective function for a population of different stacks. However I would like to constrain this optimisation so that it doesn't look at stacks with two identical layers next to each other. Currently I am doing this by putting a big penalty on such structures in the objective function.
I was wondering if there is a way to constrain the ga function such that nearest neighbour variables cannot have the same value, i.e. x1~=x2, but x1 may equal x3.

Best Answer

Expressing x1 ~= x2 could in theory be done as ((x1 - x2) < 0 or (x2 - x1) < 0) . However, you cannot express "or" in inequality constraints or equality constraints: inequality constraints and equality constraints are "and"'d together. ga() does not offer strict inequality either, so the closest you could get would be ((x1 - x2) <= 0 and (x2 - x1) <= 0) and that simplifies to x1 == x2 which is not what you want .
ga() also cannot use equality constraints when there are integer constraints.
So... you are going to have to program this as nonlinear inequality constraints.
all(abs(diff(x)) ~= 1)
would correspond to the condition being met. But that returns logical true, and nonlinear constraints are considered to be satisfied if the output of the expression is <= 0 . So you need that the expression returns false (or negative) when the condition is satisfied, and true (or positive) when the condition is violated. One way of expressing that would be:
nonlcon = @(x) deal(any(abs(diff(x)) == 1), [])
that would return true, a positive number, if there was a constraint violation, which happens to work out; the output of the expression with be 0 if the constraint is not violated, and that is the condition for _continuing. It is confusing, but self-consistent.
Related Question