Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

The complete answer would be like this.

  1. find ga function. (type "edit ga")
  2. Duplicate it, to a new function like ga_customized.
  3. edit the new created function like this :

    function [x,fval,exitFlag,output,population,scores] = ga_customized(fun,nvars,Aineq,bineq,Aeq,beq,lb,ub,nonlcon,intcon,options,extra_param)

and add this code

fun = @(x) fun(x, extra_param);

also find the code part around line 230 and edit it like this:

if nargin < 12, extra_param = [];
    if nargin < 11, options = [];
        if nargin < 10,  intcon = [];
            if nargin < 9,  nonlcon = [];
                    if nargin < 8, ub = [];
                    if nargin < 7, lb = [];
                        if nargin <6, beq = [];
                            if nargin <5, Aeq = [];
                                if nargin < 4, bineq = [];
                                    if nargin < 3, Aineq = [];
                                    end
                                 end
                            end
                        end
                    end
                end
            end
        end
    end
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top