nsga2算法中合并子代和父代种群,然后进行排序精英选择的matlab代码示例
时间: 2024-02-05 12:14:08 浏览: 89
遗传算法的matlab实例
4星 · 用户满意度95%
以下是一个简单的NSGA-II算法的Matlab代码示例,包括合并种群、非支配排序、拥挤度距离计算和选择:
```
function [pop] = nsga2(pop, pop_child, n, m)
% pop: 父代种群
% pop_child: 子代种群
% n: 种群大小
% m: 目标函数个数
% 合并种群
pop = [pop; pop_child];
% 非支配排序
front = nondominated_sort(pop, n, m);
% 计算拥挤度距离
cd = crowding_distance(pop, front, n, m);
% 选择
pop = selection(pop, front, cd, n, m);
end
function [front] = nondominated_sort(pop, n, m)
% 非支配排序
% 初始化
front(1).f = [];
sp(1:n) = 0;
np(1:n) = 0;
for i=1:n
front(i).f = [];
sp(i) = 0;
np(i) = 0;
end
% 计算支配关系
for i=1:n
for j=1:n
if i~=j
dom = dominance(pop(i,:), pop(j,:), m);
if dom == 1
sp(i) = sp(i) + 1;
elseif dom == -1
np(i) = np(i) + 1;
end
end
end
if sp(i) == 0
front(1).f = [front(1).f i];
end
end
% 非支配排序
i = 1;
while ~isempty(front(i).f)
Q = [];
for j=1:length(front(i).f)
p = front(i).f(j);
for k=1:n
if (p~=k) && (sp(k)>0)
sp(k) = sp(k) - 1;
if sp(k) == 0
Q = [Q k];
end
end
end
end
i = i + 1;
front(i).f = Q;
end
end
function [dom] = dominance(x, y, m)
% 判断x是否支配y
dom = 0;
less_eq_cnt = 0;
less_cnt = 0;
for i=1:m
if x(i) <= y(i)
less_eq_cnt = less_eq_cnt + 1;
end
if x(i) < y(i)
less_cnt = less_cnt + 1;
end
end
if less_cnt == 0 && less_eq_cnt < m
dom = 1; % x支配y
end
if less_cnt < m && less_eq_cnt == m
dom = -1; % y支配x
end
end
function [cd] = crowding_distance(pop, front, n, m)
% 计算拥挤度距离
cd = zeros(n,1);
for f=1:length(front)
fsize = length(front(f).f);
if fsize > 0
for i=1:m
temp = pop(front(f).f,:);
temp = sortrows(temp,i);
cd(front(f).f(1)) = Inf;
cd(front(f).f(fsize)) = Inf;
for j=2:fsize-1
cd(front(f).f(j)) = cd(front(f).f(j)) + (temp(j+1,i) - temp(j-1,i))/(temp(fsize,i) - temp(1,i));
end
end
end
end
end
function [pop] = selection(pop, front, cd, n, m)
% 选择
pop_new = [];
next_front = 1;
cnt = 0;
while cnt < n
if ~isempty(front(next_front).f)
if cnt + length(front(next_front).f) <= n
% 将此层全部选入
temp = pop(front(next_front).f,:);
pop_new = [pop_new; temp];
cnt = cnt + length(front(next_front).f);
next_front = next_front + 1;
else
% 按照拥挤度距离排序,并选取前n-cnt个
temp = pop(front(next_front).f,:);
[~,index] = sort(cd(front(next_front).f),'descend');
temp = temp(index,:);
pop_new = [pop_new; temp(1:n-cnt,:)];
cnt = n;
end
else
break;
end
end
pop = pop_new;
end
```
其中,`pop`和`pop_child`分别为父代和子代种群,`n`为种群大小,`m`为目标函数个数。`nondominated_sort`函数计算非支配排序,`dominance`函数判断支配关系,`crowding_distance`函数计算拥挤度距离,`selection`函数进行选择。最后,将`pop`作为算法的输出即可。
请注意,该示例代码仅供参考,具体实现可能需要根据实际情况进行调整。
阅读全文