I use the ga MATLAB optimtool to minimize an objective function.
I create two functions in the same script main.m
.
If I don't use the variable a
the genetic algorithm
works well. When I introduce the variable a
calling
it in every iteration a = fcn( a );
in the main.m
then I get an error Not enough input arguments. (line 5)
%% main function
function [x,fval,a] = main()
nvars = 1; a = 0; % assign the number of values and the variable a
a = fcn( a,t ); % call the fitness fcn
[x,fval] = ga(@(t) fcn(t),nvars);
end
%% fitness function
function [ y,a ] = fcn( a,t )
y = abs( t - 1 ); % objective fcn
a = a + 1;
end
I mention that a
is an extra variable, unrelated to ga's operation.
I realize that though Ι refresh the value a
for the first time, I don't
manage to change a
as long as the genetic algorithm iterates to find the better value.
Is there any idea? Thank you in advance!
First of all, if your goal is only to count the number of calls ga
does to your fitness function, you already have access to it via the output
output of ga
:
[x,fval,exitflag,output] = ga(fitnessfcn,nvars,...) returns output, a structure that contains output from each generation and other information about the performance of the algorithm.
When you look at what is in this output
variable, you directly find :
output =
problemtype: 'unconstrained'
rngstate: [1x1 struct]
generations: 56
funccount: 2850
message: 'Optimization terminated: average change in the fit...'
maxconstraint: []
And the number of calls to your function can be accessed via a call to output.funccount
If the question is more about how to update any extra variable in the fitness function, I think your best bet is to use global
variables :
global a
a=0;
[x,fval,output] = main();
main
functionfunction [x,fval,output] = main()
nvars = 1;
[x,fval,~,output] = ga(@fcn,nvars);
end
fcn
functionfunction [ y ] = fcn(t)
global a
y = abs( t - 1 ); % objective fcn
a = a + 1;
end
output =
problemtype: 'unconstrained'
rngstate: [1x1 struct]
generations: 100
funccount: 5050
message: 'Optimization terminated: maximum number of gener...'
maxconstraint: []
a =
5050
You can see that a
is equal to output.funccount
, meaning it has been refreshed at every fcn
call