Undefined variable in functions
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Rakesh Jain
am 24 Feb. 2017
Beantwortet: Star Strider
am 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?
0 Kommentare
Akzeptierte Antwort
Star Strider
am 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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Problem-Based Optimization Setup finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!