%% 粗糙度最小时的加工参数计算
%% 基本参数
Number=1000;% Nubmer粒子数目
weight=0.44;% 惯性因子weight
M=200;% 最大迭代系数M
Dimension=4;% 自变量的个数Dimension
c1=0.5;% 加速因子c1
c2=0.5;% 加速因子c2
format long;
%% 初始化粒子群位置和速度
for i=1:Number
for j=1:Dimension
if j==1
x(i,j)=unifrnd(80,100);
v(i,j)=unifrnd(-0.1,0.1);
end
if j==2
x(i,j)=unifrnd(3,5);
v(i,j)=unifrnd(-0.1,0.1);
end
if j==3
x(i,j)=unifrnd(140,340);
v(i,j)=unifrnd(-0.1,0.1);
end
if j==4
x(i,j)=unifrnd(140,340);
v(i,j)=unifrnd(-0.1,0.1);
end
end
end
%% 各粒子的粗糙度
for i=1:Number
Ra(i)=Roughness(x(i,1),x(i,2),x(i,3),x(i,4));
y_Ra(i,:)=x(i,:);
end
%% 找粗糙度最小的粒子的位置
position=x(Number,:);
for i=1:Number-1
if Roughness(x(i,1),x(i,2),x(i,3),x(i,4)) < Roughness(position(1),position(2),position(3),position(4))
position=x(i,:);
end
end
for t=1:M
for i=1:Number
v(i,:)=weight*v(i,:)+c1*unifrnd(0,1)*(y_Ra(i,:)-x(i,:))+c2*unifrnd(0,1)*(position-x(i,:)); %粒子新的移动速度
x(i,:)=x(i,:)+v(i,:); %新的位置
for m=1:Number
for n=1:Dimension
if n==1
if x(m,n)<80 || x(m,n)>100
x(m,n)=x(m,n)-2*v(m,n);
end
end
if n==2
if x(m,n)<3 || x(m,n)>5
x(m,n)=x(m,n)-2*v(m,n);
end
end
if n==3
if x(m,n)<140 || x(m,n)>340
x(m,n)=x(m,n)-2*v(m,n);
end
end
if n==4
if x(m,n)<140 || x(m,n)>340
x(m,n)=x(m,n)-2*v(m,n);
end
end
end
end
if Roughness(x(i,1),x(i,2),x(i,3),x(i,4)) < Ra(i)
Ra(i)=Roughness(x(i,1),x(i,2),x(i,3),x(i,4)); %更新最优粗糙度值
y_Ra(i,:)=x(i,:); %更新最优粗糙度值对应粒子位置
end
if Ra(i) < Roughness(position(1),position(2),position(3),position(4))
position=y_Ra(i,:); %更新全局最优粗糙度值对应粒子位置
end
end
X_Ra(t)=t;
Y_Ra(1,t)=position(1);%Y_Ra每次迭代的参数值
Y_Ra(2,t)=position(2);
Y_Ra(3,t)=position(3);
Y_Ra(4,t)=position(4);
end
%% 各参数的收敛情况
plot(X_Ra,Y_Ra(1,:),'y*','LineWidth',1);
xlabel('迭代次数');
title('粗糙度最优迭代过程中四参数收敛情况');
axis([0 200 0 350]);
grid on;
hold on;
plot(X_Ra,Y_Ra(2,:),'r-','LineWidth',1);
plot(X_Ra,Y_Ra(3,:),'b--','LineWidth',1);
plot(X_Ra,Y_Ra(4,:),'g.','LineWidth',1);
legend('空载电压U','峰值电流I','脉冲宽度Tw','脉冲间隔Ti');
hold off;
%% 最优解和最优值
x_best_roughness=position; %x_best_roughness是全局最优粗糙度值对应粒子位置,即最优解
f_best_roughness=Roughness(position(1),position(2),position(3),position(4)); %f_best_roughness是全局最优粗糙度值
format short;