📄 main.m
字号:
%主函数function [x Objective] = Main(PopSize, GEN, P_Crossover, P_Mutation)[x q] = Init(PopSize);[Objective chro] = evaluation(0, PopSize, x);x = chro;for i=1:GEN selection(PopSize, x, q); crossover(PopSize, P_Crossover, x); mutation(PopSize, P_Mutation, x); [Objective chro] = evaluation(i, PopSize, x); x = chro;endx(1,1)x(1,2)x(1,3)Objective(1)sqrt(x(1,1))+sqrt(x(1,2))+sqrt(x(1,3))%边界函数function [ check ] = checkbound(x)if power(x(1),2)+2*power(x(2),2)+3*power(x(3),2) > 1 check = 0;else check = 1;endfunction [ x q ] = Init(PopSize)%UNTITLED1 Summary of this function goes here% Detailed explanation goes herex = rand(PopSize+1, 3);a = 0.05;q(1) = 0.05;for i=2:PopSize+1 a = a*0.95; q(i) = q(i-1)+a;end;for i=2:PopSize+1 check = checkbound(x(i,:)); while x(i,1)<0 || x(i,2)<0 || x(i,3)<0 || check == 0 x(i,:) = rand(1,3); check = checkbound(x(i,:)); endend%目标函数function [Objective] = objective_function(PopSize, chromosome)for i=2:PopSize+1 x1 = chromosome(i,1); x2 = chromosome(i,2); x3 = chromosome(i,3); Objective(i) = sqrt(x1)+sqrt(x2)+sqrt(x3); endObjective(1) = max(Objective);%评估函数function [Objective, chro] = evaluation(gen, PopSize, chromosome)Objective = objective_function(PopSize, chromosome);[temp IX] = sort(Objective(2:PopSize+1),'descend');Objective(2:PopSize+1) = temp;for i=2:PopSize+1 chro(i,:) = chromosome(IX(i-1)+1,:);endif Objective(1) > sqrt(chro(1,1))+sqrt(chro(1,2))+sqrt(chro(1,3)) chro(1,:) = chromosome(IX(1)+1,:);end%选择函数function selection(PopSize, chromosome, q)for i=2:PopSize+1 r = rand*q(PopSize); for j=2:PopSize+1 if r <= q(j) temp(i,:) = chromosome(j,:); break; end endendfor i=2:PopSize+1 chromosome(i,:) = temp(i,:);end%交叉函数function crossover(PopSize, P_Crossover, chromosome)pop = PopSize/2;for i=2:pop+1 if rand() > P_Crossover continue; end j = round(rand()*PopSize+1); jj = round(rand()*PopSize+1); r = rand(); x = r*chromosome(j,:)+(1-r)*chromosome(jj,:); y = r*chromosome(jj,:)+(1-r)*chromosome(j,:); checkx = checkbound(x); checky = checkbound(y); if checkx == 1 chromosome(j,:) = x; elseif checky == 1 chromosome(jj,:) = y; endend%变异函数function mutation(PopSize, P_Mutation, chromosome)INFTY = 10;precision = 0.0001;for i=2:PopSize+1 if rand() > P_Mutation continue; end x = chromosome(i,:); for k=1:3 if rand() < 0.5 direction(k) = rand()*2-1; else direction(k) = 0; end end infty = rand()*INFTY; while infty > precision for j=1:3 y(j) = x(j)+infty*direction(j); end check = checkbound(y); if check == 1 chromosome(i,:) = y; break; end infty = rand()*infty; endend
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -