フィルターのクリア

Undefined variable in functions

1 回表示 (過去 30 日間)
Rakesh Jain
Rakesh Jain 2017 年 2 月 24 日
回答済み: Star Strider 2017 年 2 月 24 日
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?

採用された回答

Star Strider
Star Strider 2017 年 2 月 24 日
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 件)

カテゴリ

Help Center および File ExchangeProblem-Based Optimization Setup についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by