Clear Filters
Clear Filters

Undefined variable in functions

3 views (last 30 days)
Rakesh Jain
Rakesh Jain on 24 Feb 2017
Answered: Star Strider on 24 Feb 2017
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?

Accepted Answer

Star Strider
Star Strider on 24 Feb 2017
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.

More Answers (0)

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!