# problem in optimization by MATLAB using genetic algorithm

1 view (last 30 days)
Ola Belal on 25 Nov 2019
Commented: Ola Belal on 5 Dec 2019
the first picture is the fitness equation code then I checked the function code and it works, after that I write the following codes in a new script called main and after that i have save this script, but when I write ' main' in the command window it gives me such errors Stephan on 25 Nov 2019
Change myFitness.m to:
function y = myFitness(x)
s = x(1)
z = x(3)
x = x(2)
end
also change this line your main function to:
[x, fval] = ga(...)
Reason:
The optimizers in Matlab wil accept all the single optimization variables only as a vector. To pass additional vectors / values to the objective function see passing extra parameters.

Ola Belal on 26 Nov 2019
thank you for your help but when I try it it does not work I mean the fitness function
%% Fitness function
function y = myFitness(x)
s = x(1);
z = x(3);
x = x(2);
y= -10.40046+(0.355400*s)+(0.544964*x)+(181.61679*z)-(0.002437*s*x)-(0.765260*s*z)-(0.224846*x*z)-(0.000453*(s^2))-(0.006994*(x^2))-(577.65313*(z^2));
end
when I try if the equation works in the command window by adding values for (s,x and z) I get this
>> myFitness(21,30,0.2)
Error using myFitness
Too many input arguments.
also I have make the changes to the main function
%% main function - minimization
clc, clear, close all
FitFcn = @myFitness;
nvars = 3;
[x, fval] = ga(FitFcn,nvars);
when I write main still I get errors.
thank you.
Stephan on 26 Nov 2019
When i run this code it works fine:
%% main function - minimization
clc, clear, close all
FitFcn = @myFitness;
nvars = 3;
[x, fval] = ga(FitFcn,nvars)
%% Fitness function
function y = myFitness(x)
s = x(1);
z = x(3);
x = x(2);
y= -10.40046+(0.355400*s)+(0.544964*x)+(181.61679*z)-(0.002437*s*x)-(0.765260*s*z)-(0.224846*x*z)-(0.000453*(s^2))-(0.006994*(x^2))-(577.65313*(z^2));
end
ends with:
Optimization terminated: maximum number of generations exceeded.
x =
1.0e+03 *
-0.2452 -0.4133 -2.1707
fval =
-2.7229e+09
The message problably is a result of unconstrained optimization - but it works as it should.
Ola Belal on 5 Dec 2019