Effacer les filtres
Effacer les filtres

Undefined variable in functions

1 vue (au cours des 30 derniers jours)
Rakesh Jain
Rakesh Jain le 24 Fév 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?

Réponse acceptée

Star Strider
Star Strider le 24 Fév 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.

Plus de réponses (0)

Catégories

En savoir plus sur Problem-Based Optimization Setup dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by