I am using the MATLAB optimtool for genetic algorithm optimization.
I am opening a new script with the name 'm_0a4'
FitnessFunction = @m_0b4;
NumberOfVariables = 1;
[x,fval] = ga(FitnessFunction, numberOfVariables);%Here I minimize the difference y
I am opening a second new script naming it 'm_0b4'
function y = m_0b4(x)
prompt = 'write it down';
i = input(prompt) %the input value
y = x - i; % the variable I want to minimize
The functionnn m_0b4 request me for a value 'i' and I am typing the input,
The script m_0a4 of genetic algorithm calls the 'y'.
As I type the value, MATLAB keep on requesting me again for a value. When I am typing 'Enter' MATLAB brings me an error.
Assignment has more non-singleton rhs dimensions than
non-singleton subscripts
Caused by:
Failure in user-supplied fitness function evaluation.
GA cannot continue.
I cant think why MATLAB doesn't understand that I give an input (for example the number 5). Is there any idea?
Thank you in advance!
I think what you should do would be to ask the user for the input once before the call to ga
.
In order for your function m_0b4
to take this input into account, you can declare FitnessFunction
as an anonymous function of 1 argument :
Your new function :
function y = m_0b4(x,i)
y = x - i;
end
In the Main script :
prompt = 'write it down';
i = input(prompt)
% Declare your fitness function that will be executed with the input entered by the user
FitnessFunction=@(x) m_0b4(x,i);
% Minimize
NumberOfVariables = 1;
[x,fval] = ga(FitnessFunction, NumberOfVariables);
The function you're trying to minimize tends to -infinity when x tends to -infinity....
function y = m_0b4(x,i)
y = abs(x - i);
end
Result :
With an input i
set to 20 (And a maximum of 100 generations) :
x =
20.012668610027522
fval =
0.012668610027522