function mainFunc
clear; clf; clc;
%% Step 1: Initialization
% Encode real numbers between [0, 10] into binary string with length of 10
popsize = 20; % population size
chromlength = 10; % individual length
pc = 0.6; % cross-over probability
pm = 0.6; % mutation probability
pop = round(rand(popsize, chromlength)); % initial population, each row ...
% corresponds to a real number ...
% between [0, 10]
%% Step 2: Evolve with generic algorithm
maxIter = 20;
x = zeros(maxIter, 1);
y = zeros(maxIter, 1); % max values of each iteration
for iter = 1: maxIter %
disp(['The ', num2str(iter), '-th iteration !']);
objvalue = objective(pop); % popsize * 1 vector
fvalue=fitvalue(objvalue); % calculate fit values
% fvalue
newpop = selection(pop, fvalue); % selection procedure
% newpop
newpop = crossover(newpop, pc); % cross-over procedure
newpop = mutation(newpop, pm); % mutation procedure
[bestfit, index] = max(fvalue);
bestindividual = pop(index, :);
y(iter) = bestfit;
x(iter)=decodechrom(bestindividual, 1, chromlength) * 10 / 1023;
pop=newpop;
end
fplot('10*sin(5*x)+7*cos(4*x)',[0 10])
hold on
plot(x, y, 'r*')
hold off
end
%% Below are some functions used in the main function
function objvalue = objective(pop)
% objective: calculate value of 10 * sin(5 * x) + 7 * cos(4 * x)
%
% Inputs
% pop : popsize * chromlength matrix
%
% Outpus
% objvalue : popsize * 1 vector
x = decodechrom(pop, 1, 10) * 10 / 1023;
objvalue = 10 * sin(5 * x) + 7 * cos(4 * x); % popsize * 1 vector
end
function fvalue = fitvalue(objvalue)
% fitvalue: calculate the fit values of individuals
%
% Inputs
% objvalue : popsize * 1 vector
%
% Outputs
% fvalues : popsize * 1 vector
fvalue = max(objvalue, 0); % Since we are maximizing the objective ...
% use the obj_value as fit_value directly
end
function popdecimal = decodechrom(pop, spoint, length)
% decodechrom: decode chromosome from binary to decimal
%
% Inputs
% pop : popsize * chromlength matrix
% spoint : start point of the string to be decoded
% length : length of the chromosome to be decoded
%
% Outputs
% popdecimal : popsize * 1 vector
popdecimal = decodebinary(pop(:, spoint: spoint + length - 1));
end
function popdecimal = decodebinary(pop)
% decodebinary : convert binary string to a decimal integer
%
% Inputs
% pop : popsize * chromlength matrix
%
% Outputs
% popdecimal : popsize * 1 vector
[px, py] = size(pop);
pop_temp = zeros(px, py);
for i = 1: py
pop_temp(:, i) = 2 .^ (py - i) .* pop(:, i);
end
popdecimal = sum(pop_temp, 2); % sum along each row
end
评论0