Issue with PopulationSize in Genetic Algorithm toolbox
46 ビュー (過去 30 日間)
古いコメントを表示
There is a project I wanted to use the genetic algorithm tools on and attempted to rig a basic script to test it out. However, I could not run the code because it kept giving me the following error.
Error using gaoptimset>checkfield (line 436)
Invalid value for OPTIONS parameter PopulationSize: must be a positive numeric (not a character vector).
I didn't understand where I had specified PopulationSize as a character vector, so I used optimoptions to change PopulationSize to 50 manually. However it kept throwing me the same error.
When stepped through the program, I entered ga() and found that the default value for PopulationSize is the character vector '50 when numberOfVariables <= 5, else 200' which obviously isn't a numeric value. In any case, this value is supposed to be overridden when optimoptions is used to specify a value other than the default, but it didn't.
Am I doing something wrong or is the genetic algorithm solver broken? Code is as follows.
Further details is that I am doing this on my laptop with a copy of MATLAB R2024b downloaded on it. I have the Global Optimization toolbox installed.
% Testing Genetic Algorithm
clc, clear, close all
rng default % For reproducibility
numberOfVariables = 2;
lb = [-3,-3];
ub = [3,3];
a = 0.1;
b = 0.05; % define constant values
FitnessFunction = @(x) test_fitness(x,a,b);
options = optimoptions("ga",PopulationSize=50);
[x,fval] = ga(FitnessFunction,2,[],[],[],[],lb,ub,[],options);
4 件のコメント
Torsten
約4時間 前
編集済み: Torsten
約4時間 前
According to this page
"PopulationSize" is to be prescribed as a positive integer, not as a character.
But if the above code doesn't work on your computer, I cannot tell you what the problem is.
Maybe you have a second function "ga.m" on your computer ? What do you get if you type
which -all ga.m
Maybe there is confusion between MATLAB's "ga" and the Genetic Algorithm Toolbox under
?
採用された回答
Star Strider
約11時間 前
編集済み: Star Strider
約11時間 前
The problem is that the arguments to ga are defined by thier positions, and there have to be 10 arguments before the 'options' argument at the end. Adding one more '[],' before hte 'options' argument solves that problem.
All it needs now is the 'test_fitness' function to be defined, and it should work.
Try something like this --
% Testing Genetic Algorithm
clc, clear, close all
rng default % For reproducibility
numberOfVariables = 2;
lb = [-3,-3];
ub = [3,3];
a = 0.1;
b = 0.05; % define constant values
FitnessFunction = @(x) test_fitness(x,a,b);
options = optimoptions("ga",PopulationSize=50);
[x,fval] = ga(FitnessFunction,2,[],[],[],[],lb,ub,[],[],options);
.
EDIT -- (26 Jan 2026 at 18:01)
Minor text tweaks.
.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Genetic Algorithm についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!