How to add constraint with condtions using fmincon?
Show older comments
I have am optimization problem with two variables x and y where x and y are vectors.
I would like to add the foollowing constraint to fmincon :
if a<b then x<y
where a and b are known values.
I would like also to add in general x<y for every value of both vectors.
Many thanks!
Accepted Answer
More Answers (3)
xi
on 13 Oct 2019
1 vote
Ask yourself 3 question: How many vairable? how many constraints? and then how to write A and b.
Now you are saying L is a known vector, then, your vairables are just X of length N. you can write your constraint in this way:
-----------------------------
A=zeros(N^2, N);
b=ones(N^2,1);
count=0;
for i=1:N
for j=1:N
count=count+1;
A(count,i)=1;
A(count,j)=-1;
b(count)= 1/(L(i)<L(j))-1;
end
end
---------------------------------
or using N(N-1)/2 constraints instead of N^2
for i=1:N-1
for j=i:N
................
end
end
---------------------------------------
A better way is to sort L first, and get the ordering index using [~,index] = sort(L)
So you define your new variable X'=X(index); and solve X' instead.
then, you only need to write N-1 constraints:
X'(1)<X'(2), X'(2)<X'(3), ... X'(N-1)<X'(N)
b is simply b=zeros(N-1,1); You can figure out A. This should be much faster.
6 Comments
wiem abd
on 13 Oct 2019
xi
on 13 Oct 2019
forget about solution 2,I was wrong, i,j are not switchable. Solution 3 is really what you should go for:
Just One loop over i=1:N-1 A(count,index(i))=1; A(count,index(i+1))=-1;
wiem abd
on 13 Oct 2019
wiem abd
on 13 Oct 2019
xi
on 13 Oct 2019
no longer need count, just A(i, index(i)), or you need count++
wiem abd
on 14 Oct 2019
wiem abd
on 14 Oct 2019
2 Comments
Now you have 2N variables, and 2*(N-1) constraints, only need small modifications of the above code
A=zeros(2*(N-1), 2*N);
[~,index] = sort(L)
for i=1:N-1 % write two constraints for each i
A(i,index(i))=1;
A(i,index(i+1))=-1;
% ******* just add two lines here, I leave it to you to figure out what the index of A should be.
end
b=zeros(N-1,1);
wiem abd
on 22 Oct 2019
0 votes
Categories
Find more on Dynamic System Models in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!