MATLAB: Undefined variable in functions

functionmatlab function

Following is the file simplefitnes.m
function y = simple_fitnes(x)
y = p * (x(1)^2 - x(2)) ^2 + (1 - x(1))^2;
end
The file below is abc.m
FitnessFunction = @simple_fitnes;
p = input('p')
numberOfVariables = 2;
[x,fval] = ga(FitnessFunction,numberOfVariables)
When I run abc.m get an error "Undefined function or variable p. What is the error I am making? How to rectify it?

Best Answer

You have to pass ‘p’ as a variable to your ‘simple_fitnes’ function. To do that, you first have to add it as an input argument to ‘simple_fitnes’, and then create the function handle for ‘simple_fitnes’ that passes ‘p’ to it, but is ‘invisible’ to the ga function.
This does exactly that:
function y = simple_fitnes(x,p)
y = p * (x(1)^2 - x(2)) ^2 + (1 - x(1))^2;
end
p = input('p = ')
FitnessFunction = @(x)simple_fitnes(x,p);
numberOfVariables = 2;
[x,fval] = ga(FitnessFunction,numberOfVariables)
See the documentation on Anonymous Functions in Function Basics for details on how the anonymous function call works here.