Genetic algorithm- error when providing constraints in a loop

Hi. I am using ga for a problem with multiple constraints. I provide constraints in a for loop using the comand "vercat" and I get the following error on execution
Not enough input arguments.
Error in simple_constraint (line 13)
c=vertcat(c,(sum(x(cin)))-1);
Does GA allow this? or I will have to hardcode each constraint? Please guide.

9 个评论

function [c, ceq] = simple_constraint(x)
global M K N D C R F inex insa inea insb ineb
%c=[sum(x(insa:inea))-K];
c=[];
start=insa;
cin=zeros(1,K);
cin(1)=start;
for n=1:N
for m=1:M
for k=2:K
cin(k)=cin(k-1)+M;
end
c=vertcat(c,(sum(x(cin)))-1);
cin=zeros(1,K);
cin(1)=start+1;
end
start=n*K*M+1;
cin(1)=start;
end
I created global variables just to play with indices, as my opt. variables are 3D arrays transforned to vector x. The error occurs at the statement of "vercat" when I debug.
function y=simple_fitness(x)
global M K N D C R F inex insa inea insb ineb
v1=x(1:inex);
x1=reshape(v1,M*N);
x1=permute(x1,[2 1]);
v2=x(insa:inea);
a=reshape(v2,K,M,N);
a=permute(a,[2 1 3]);
v3=x(insb:ineb);
b=reshape(v3,K,M,N);
b=permute(b,[2 1 3]);
trans=a.*b.*R;
comp=a.*F;
cyc=D.*C;
y=sum(D./(sum(sum(trans,3),2)))+max((cyc)./(sum(sum(comp,3),2)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Genetic Algorithm main
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
ObjectiveFunction = @simple_fitness;
nvars = length(x); % Number of variables
LB(1:length(x)) = 0; % Lower bound
UB(1:length(x)) = 1; % Upper bound
ConstraintFunction = @simple_constraint;
[x,fval] = ga(ObjectiveFunction,nvars,[],[],[],[],LB,UB, ...
ConstraintFunction,[1:inea]);
The portion starting from the %%%% appears to belong to a separate file. However if that code is moved to a separate file, then x and inea are not defined.
Your code uses K, M, N as sizes for reshape() purposes, but never assigns values to them. As they are global variables, they will be initialized to [] (the empty array), which is going to lead to problems in execution.
The portion starting from the %%%%%% is the main file, I have intiliazed all the variables including K,M,N in the main file and made them global to be accessable in other files. so they are not being initilizaed to [] an empty array. rather they have values.
excluding the use of global variables, I have tried the follwoing constraint which is hard coded as
c=[x(3)+x(4)+x(5)+x(6)+x(7)+x(8)+x(9)+x(10)+x(11)+x(12)+x(13)-2];
but the error is same.
We can make guesses, but it is difficult to reproduce that behaviour without the actual code.

请先登录,再进行评论。

回答(0 个)

类别

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by