Optimization, optimconstr: Unable to perform assignment because the left and right sides have a different number of elements.
Show older comments
This is a program about optimization. I use con=optimiconstr() and for loop to read the constraints. But Matlab shows something wrong with my code as follows. I don't know why it is wrong. Could you give me some tips?
clear;
data=[9.4888 8.7928 11.5960 11.5643 5.6756 9.8497 9.1756 13.1385 15.4663 15.5464;
5.6817 10.3868 3.9294 4.4325 9.9658 17.6632 6.1517 11.8569 8.8721 15.5858];
d=zeros(10);
for i=1:9
for j=2:10
if j>i
d(i,j)=norm(data(:,i)-data(:,j));
end
end
end
x=optimvar('x',10,1,LowerBound=0,UpperBound=1,Type='integer');
y=optimvar('y',10,10,LowerBound=0,UpperBound=1,Type='integer');
prob=optimproblem("ObjectiveSense","min");
prob.Objective=sum(x);
% Above are initiation, and constraints are as follows.
con=optimconstr(32,1);
con(32)=sum(y,1)>=1;% Matlab says here "Unable to perform assignment because
% the left and right sides have a different number of elements."
con(31)=sum(y,2)<=5;% Matlab says here the same mistake too as above.
for i=1:10
for j=1:10
con(i)=d(i,j)*y(i,j)<=10*x(i);
con(i+10)=x(i)>=y(i,j);
end
con(i+20)=x(i)==y(i,i);
end
prob.Constraints=con;
[s,fval]=solve(prob);
show(prob);
s.x
s.y
fval
However, if I write the constraints in another way in which I don't use con=optimconstr(), then the program can run:
clear;
data=[9.4888 8.7928 11.5960 11.5643 5.6756 9.8497 9.1756 13.1385 15.4663 15.5464;
5.6817 10.3868 3.9294 4.4325 9.9658 17.6632 6.1517 11.8569 8.8721 15.5858];
d=zeros(10);
for i=1:9
for j=2:10
if j>i
d(i,j)=norm(data(:,i)-data(:,j));
end
end
end
x=optimvar('x',10,1,LowerBound=0,UpperBound=1,Type='integer');
y=optimvar('y',10,10,LowerBound=0,UpperBound=1,Type='integer');
prob=optimproblem("ObjectiveSense","min");
prob.Objective=sum(x);
% Above are initiation (same as the first program), and constraints are as follows.
con1=[1<=sum(y)';sum(y,2)<=5];% I don't use con=optimconstr(), I just create an ordinary vector.
con2=[];
for i=1:10
con2=[con2;x(i)==y(i,i)];
for j=1:10
con1=[con1;d(i,j)*y(i,j)<=10*x(i);y(i,j)<=x(i)];
end
end
prob.Constraints.con1=con1;
prob.Constraints.con2=con2;
[s,fval]=solve(prob);
s.x
s.y
fval
Accepted Answer
More Answers (0)
Categories
Find more on Solver Outputs and Iterative Display 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!