q = zeros(1,k);

aa = zeros(1,k);

p = zeros(1,k);

bb = zeros(2,k);

tt0 = zeros(1,k);

minx = zeros(k,G);

for l = 1:k

t0 = cputime;

x = rand(D,NP)*(Xs-Xx)+Xx; % 赋初值

for m = 1:NP

Ob(m) = ackley(x(:,m));

end

trace(1) = min(Ob);

minx(l,1) = trace(1);

% 差分操作

for gen = 1:G

% r1,r2,r3和m互不相同

for m = 1:NP

r1 = randi([1,NP],1,1);

while(r1 == m)

r1 = randi([1,NP],1,1);

end

r2 = randi([1,NP],1,1);

while(r2 == m)|(r2 == r1)

r2 = randi([1,NP],1,1);

end

r3 = randi([1,NP],1,1);

while((r3 == m)|(r3 == r1)|(r3 == r2))

r3 = randi([1,NP],1,1);

end

v(:,m) = x(:,r1)+F*(x(:,r2)-x(:,r3));

end

r = randi([1,NP],1,1);

for n = 1:D

cr = rand(1);

if(cr

u(n,:) = v(n,:);

else

u(n,:) = x(n,:);

end

end

% 边界吸收

for n = 1:D

for m = 1:NP

if u(n,m)

u(n,m) = Xx;

end

if u(n,m)>Xs

u(n,m) = Xs;

end

end

end

for m = 1:NP

Ob1(m) = ackley(u(:,m));

end

for m = 1:NP

if Ob1(m)

x(:,m) = u(:,m);

end

end

for m = 1:NP

Ob(m) = ackley(x(:,m));

end

trace(gen+1) = min(Ob);

minx(l,gen+1) = trace(gen+1);

end

[SortOb,Index] = sort(Ob);

x = x(:,Index);

X = x(:,1); % 最优变量

q(1,l)=X(1,1);

aa(1,l)=X(2,1);

bb(1,l)=q(1,l);

bb(2,l)=aa(1,l);

Y = min(Ob); % 最优值

p(:,l)=Y;

disp('最优变量:');

disp(X);

disp('最优值:');

disp(Y);

fprintf('DE所耗时间为:%f\n',cputime - t0);

tt0(1,l)=cputime - t0;

end

figure

plot(1:1:k,tt0);

figure

plot(1:1:G+1,mean(minx))

xlabel('迭代次数');

ylabel('目标函数值');

title('DE目标函数曲线');