MATLAB: Error in the code metioned below

gaMATLAB

%%Fitness function
function MCWQIAVG = mytrial(D1,D2,D3)
FEavgx = 0;
FEavgy = 0;
FEavgz = 0;
for t = 1:26
x = D1*exp(0.03*t);
if x>=0 && x<=0.1
FE = 1;
end
if x>0.1 && x<0.2
FE = -10*x+2;
end
if x>=0.2 && x<=0.5
FE = 0;
end
if x>0.5 && x<0.6
FE = 10*x-5;
end
if x>=0.6 && x<=1
FE = 1;
end
FEavgx = (FEavgx + FE)/2;
end
for t = 1:26
x = D2*exp(0.03*t);
if x>=0 && x<=0.1
FE = 1;
end
if x>0.1 && x<0.2
FE = -10*x+2;
end
if x>=0.2 && x<=0.5
FE = 0;
end
if x>0.5 && x<0.6
FE = 10*x-5;
end
if x>=0.6 && x<=1
FE = 1;
end
FEavgy = (FEavgy + FE)/2;
end
for t = 1:26
x = D3*exp(0.03*t);
if x>=0 && x<=0.1
FE = 1;
end
if x>0.1 && x<0.2
FE = -10*x+2;
end
if x>=0.2 && x<=0.5
FE = 0;
end
if x>0.5 && x<0.6
FE = 10*x-5;
end
if x>=0.6 && x<=1
FE = 1;
end
FEavgz = (FEavgz + FE)/2;
end
MCWQIx = 100-(FEavgx/(0.05*FEavgx+0.05));
MCWQIy = 100-(FEavgy/(0.05*FEavgy+0.05));
MCWQIz = 100-(FEavgz/(0.05*FEavgz+0.05));
MCWQIAVG = (MCWQIx + MCWQIy + MCWQIz)/3;
end
%%this is the fitness function that I have defined and the main portion is mentioned below
rng default
fitnessfcn = @mytrial
nvars = 3;
lb = [0.2,0.2,0.2];
ub = [0.4,0.4,0.4];
[x,favl]= ga(fitnessfcn,nvars,lb,ub)
%they are showing an error in the main portion mentioned above
%need help in correcting the error

Best Answer

You have at least two problems with your code.
The first is that your mytrial function does not satisfy the requirements imposed by ga on its first input. From the ga documentation page the first input must be an "Objective function, specified as a function handle or function name. Write the objective function to accept a row vector of length nvars and return a scalar value." Yours instead accepts three separate inputs.
The second is that your if "switchyards" do not handle the cases where x is outside the range [0, 1]. Can this happen? For the right value of D1, easily.
D1 = 1;
x = D1*exp(0.03*1)
x = 1.0305
You could simplify your code a bit using logical indexing.
FE = zeros(1, 26); % I'm assuming FE should be 0 if x is outside [0, 1]
t = 1:26;
x = D1*exp(0.03*t);
FE(x >= 0 & x <= 0.1) = 1;
case2 = x > 0.1 & x < 0.2;
FE(case2) = -10*x(case2) + 2;
% Etc for cases 3, 4, and 5
Now do whatever you need using the elements of FE.