0

我想在 matlab 中使用遗传算法找到函数的最小值(我知道 matlab 有 GA 工具箱,但我想以编程方式实现它)。我有四个 m 文件,迭代 50 次,并且在每个循环步骤中保存最佳平均适应度,但是当我运行此代码时,代码不会在最佳和平均中返回较低的值,这是不正常的。我的问题在哪里?

我的数学函数是 find minmun of f(x)= -|x*sin(sqrt(|x|))|

主文件

global population;
global fitness;
global popsize;
format bank;
popsize=50;
report=zeros(popsize,2);
selected=ones(1,50);
fitness=zeros(1,50);
population = randi([0 1], 50, 10);
for j=1:popsize
calFitness();
for i=1:popsize
   selected(1,i)=(rol_wheel(fitness));
end;
population =recombin(population,selected);
report(j,:)=[min(fitness),mean(fitness)];
end

加州健身

function [] = calFitness(  )
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
global population;
global fitness;
global popsize;
%population=population.*2;
for i=1:popsize
    x=bin2dec(num2str(population(i,:)))/2;
    fitness(1,i)= abs(x*sin(sqrt(abs(x))));

 %disp(fitness);
end

%disp();

滚轮

% ---------------------------------------------------------
% Roulette Wheel Selection Algorithm. A set of weights
% represents the probability of selection of each
% individual in a group of choices. It returns the index
% of the chosen individual.
% Usage example:
% fortune_wheel ([1 5 3 15 8 1])
%    most probable result is 4 (weights 15)
% ---------------------------------------------------------
function choice = rol_wheel(weights)
  accumulation = cumsum(weights);
  p = rand() * accumulation(end);
  chosen_index = -1;
  for index = 1 : length(accumulation)
    if (accumulation(index) > p)
      chosen_index = index;
      break;
    end
  end
  %keyboard
  choice = chosen_index;

重组

function pop = recombin( popu,selected )
global popsize;
pop=zeros(50,10);
for i=1:popsize/2
    rc=randi([1,10]);
    for j=1:10
            pop(i,1:rc-1)=popu(selected(i),1:rc-1);
            pop(i,rc:end)=popu(selected(i+25),rc:end);
            pop(i+25,1:rc-1)=popu(selected(i+25),1:rc-1);
            pop(i+25,rc:end)=popu(selected(i),rc:end);
          %keyboard
    end
end  
end

我将不胜感激任何答案和帮助。

4

0 回答 0