Search code examples
matlabargumentsgenetic-algorithm

Pass Optional Variable in Matlab Genetic Algorithm


I have a problem in coding my Genetic Algorithm using Matlab. I am using the ga function and I have no problem with the concepts of ga and how it works. For implementing my object function, I need to pass an extra variable to this function (In addition to the parameters vector). (What I intend is actually trying to mix fittings of different plot and I am integrating the ga function of Matlab in another code of mine). I have tried using global variables and it works fine. But I was just wondering is there any other solution for this problem? As the global variable starts to become bigger and bigger for later tasks.


Solution

  • You might want to read up on function handles - particularly parameterising function handles. This lets you 'bind in' extra arguments to your objective function. For example, instead of

    ga(@myfcn, ...);
    

    You might say

    param = 17;
    fh = @(x) myfcn(x, param);
    ga(fh, ...);
    

    and so myfcn always gets 17 as its second argument.