How to incorporate write "options" into the main code (GA algorithm) for beginners

1 view (last 30 days)
I am a beginner to writing matlab code for global optimization using GA algorithm. I can use the live editor to perform the optimization. However, I noticed more than one peak from the resulting plots. It means that there may be more than one optimum conditions. So I would like to write a code that can change number of parents, and at each number of parents, the GA optimization should give me a new set of solutions.
To accomplish this, I wen to this website,, and found that I should use options to pass these extra information to my code. This is where the problem started. I don't understand how to incorporate the inforamtion in the link above to my existing main code.
I know that I should write the following two lines:
options = optimoptions('ga','Option1','value1','Option2','value2'); (1)
[x,fval] = ga(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon,options) (2)
To change number of parents, the link above said...
A function handle enables you to write your own selection function.
options = optimoptions('ga','SelectionFcn',@myfun); (3)
Your selection function must have the following calling syntax:
function parents = myfun(expectation, nParents, options) (4)
ga provides the input arguments expectation, nParents, and options. Your function returns the indices of the parents.
To get x and fval, should start with Line 3, followed by Lines 4 and 2?

Answers (1)

Alan Weiss
Alan Weiss on 21 Jan 2022
I think that you have a misconception about How the Genetic Algorithm Works. ga always takes exactly two parents for creating a child, except when it takes one for a mutation child.
There may indeed be more than one optimum, but it doesn't mean that you should do any parameter tuning to run your optimization. Please read up on this and other topics in the genetic algorithm documentation such as
Good luck,
Alan Weiss
MATLAB mathematical toolbox documentation
  1 Comment
Nanthiya Hansupalak
Nanthiya Hansupalak on 21 Jan 2022
Thank you.
However, the website that I found stated that the number of parents does affect the solution. Anyway, the problem that I have is how to incorporate Lines 3 and 4 to Line 2 in my questions. The documentation on this is not clear to a beginner like me. Please anyone kindly explain it. Your help will be appreciated.

Sign in to comment.




Community Treasure Hunt

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

Start Hunting!

Translated by