我的毕设只用把PID和模糊PID相比较
常规PID,用Matlab里的Simulink模块仿真,建立你要做的动力学模型的传函或者状态空间。PID参数调节可用临界比度法。
模糊PID就麻烦了,打开Matlab中FIS模块,一般都用二阶模糊?输入E,EC的隶属函数,一般为高斯,和输出模糊Kp,Ki,Kd,一般为三角。还要整定模糊规则,再加载到Simulink里。调节模糊因子Gu,Ge,Gec,设置模糊PID的参数。
总之,你这个问题在白度知道里很难说清楚。
这个问题也困扰了我好久,终于解决了。给你个gam程序,新建m文件复制进去,再运行程序试试。
%gam
function [x,endPop,bPop,traceInfo] = ga(bounds,evalFN,evalOps,startPop,opts,
termFN,termOps,selectFN,selectOps,xOverFNs,xOverOps,mutFNs,mutOps)
% GA run a genetic algorithm
% function [x,endPop,bPop,traceInfo]=ga(bounds,evalFN,evalOps,startPop,opts,
% termFN,termOps,selectFN,selectOps,
% xOverFNs,xOverOps,mutFNs,mutOps)
%
% Output Arguments:
% x - the best solution found during the course of the run
% endPop - the final population
% bPop - a trace of the best population
% traceInfo - a matrix of best and means of the ga for each generation
%
% Input Arguments:
% bounds - a matrix of upper and lower bounds on the variables
% evalFN - the name of the evaluation m function
% evalOps - options to pass to the evaluation function ([NULL])
% startPop - a matrix of solutions that can be initialized
% from initializem
% opts - [epsilon prob_ops display] change required to consider two
% solutions different, prob_ops 0 if you want to apply the
% genetic operators probabilisticly to each solution, 1 if
% you are supplying a deterministic number of operator
% applications and display is 1 to output progress 0 for
% quiet ([1e-6 1 0])
% termFN - name of the m termination function (['maxGenTerm'])
% termOps - options string to be passed to the termination function
% ([100])
% selectFN - name of the m selection function (['normGeomSelect'])
% selectOpts - options string to be passed to select after
% select(pop,#,opts) ([008])
% xOverFNS - a string containing blank seperated names of Xoverm
% files (['arithXover heuristicXover simpleXover'])
% xOverOps - A matrix of options to pass to Xoverm files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([2 0;2 3;2 0])
% mutFNs - a string containing blank seperated names of mutationm
% files (['boundaryMutation multiNonUnifMutation
% nonUnifMutation unifMutation'])
% mutOps - A matrix of options to pass to Xoverm files with the
% first column being the number of that xOver to perform
% similiarly for mutation ([4 0 0;6 100 3;4 100 3;4 0 0])
% Binary and Real-Valued Simulation Evolution for Matlab
% Copyright (C) 1996 CR Houck, JA Joines, MG Kay
%
% CR Houck, JJoines, and MKay A genetic algorithm for function
% optimization: A Matlab implementation ACM Transactions on Mathmatical
% Software, Submitted 1996
%
% This program is free software; you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation; either version 1, or (at your option)
% any later version
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE See the
% GNU General Public License for more details A copy of the GNU
% General Public License can be obtained from the
% Free Software Foundation, Inc, 675 Mass Ave, Cambridge, MA 02139, USA
%%$Log: gam,v $
%Revision 110 1996/02/02 15:03:00 jjoine
% Fixed the ordering of imput arguments in the comments to match
% the actual order in the ga function
%
%Revision 19 1995/08/28 20:01:07 chouck
% Updated initialization parameters, updated mutation parameters to reflect
% b being the third option to the nonuniform mutations
%
%Revision 18 1995/08/10 12:59:49 jjoine
%Started Logfile to keep track of revisions
%
n=nargin;
if n<2 | n==6 | n==10 | n==12
disp('Insufficient arguements')
end
if n<3 %Default evalation opts
evalOps=[];
end
if n<5
opts = [1e-6 1 0];
end
if isempty(opts)
opts = [1e-6 1 0];
end
if any(evalFN<48) %Not using a m file
if opts(2)==1 %Float ga
e1str=['x=c1; c1(xZomeLength)=', evalFN ';'];
e2str=['x=c2; c2(xZomeLength)=', evalFN ';'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits); endPop(j,xZomeLength)=',
evalFN ';'];
end
else %Are using a m file
if opts(2)==1 %Float ga
e1str=['[c1 c1(xZomeLength)]=' evalFN '(c1,[gen evalOps]);'];
e2str=['[c2 c2(xZomeLength)]=' evalFN '(c2,[gen evalOps]);'];
else %Binary ga
e1str=['x=b2f(endPop(j,:),bounds,bits);[x v]=' evalFN
'(x,[gen evalOps]); endPop(j,:)=[f2b(x,bounds,bits) v];'];
end
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<12 %Default muatation information
if opts(2)==1 %Float GA
mutFNs=['boundaryMutation multiNonUnifMutation nonUnifMutation unifMutation'];
mutOps=[4 0 0;6 termOps(1) 3;4 termOps(1) 3;4 0 0];
else %Binary GA
mutFNs=['binaryMutation'];
mutOps=[005];
end
end
if n<10 %Default crossover information
if opts(2)==1 %Float GA
xOverFNs=['arithXover heuristicXover simpleXover'];
xOverOps=[2 0;2 3;2 0];
else %Binary GA
xOverFNs=['simpleXover'];
xOverOps=[06];
end
end
if n<9 %Default select opts only ie roullete wheel
selectOps=[];
end
if n<8 %Default select info
selectFN=['normGeomSelect'];
selectOps=[008];
end
if n<6 %Default termination information
termOps=[100];
termFN='maxGenTerm';
end
if n<4 %No starting population passed given
startPop=[];
end
if isempty(startPop) %Generate a population at random
%startPop=zeros(80,size(bounds,1)+1);
startPop=initializega(80,bounds,evalFN,evalOps,opts(1:2));
end
if opts(2)==0 %binary
bits=calcbits(bounds,opts(1));
end
xOverFNs=parse(xOverFNs);
mutFNs=parse(mutFNs);
xZomeLength = size(startPop,2); %Length of the xzome=numVars+fittness
numVar = xZomeLength-1; %Number of variables
popSize = size(startPop,1); %Number of individuals in the pop
endPop = zeros(popSize,xZomeLength); %A secondary population matrix
c1 = zeros(1,xZomeLength); %An individual
c2 = zeros(1,xZomeLength); %An individual
numXOvers = size(xOverFNs,1); %Number of Crossover operators
numMuts = size(mutFNs,1); %Number of Mutation operators
epsilon = opts(1); %Threshold for two fittness to differ
oval = max(startPop(:,xZomeLength)); %Best value in start pop
bFoundIn = 1; %Number of times best has changed
done = 0; %Done with simulated evolution
gen = 1; %Current Generation Number
collectTrace = (nargout>3); %Should we collect info every gen
floatGA = opts(2)==1; %Probabilistic application of ops
display = opts(3); %Display progress
while(~done)
%Elitist Model
[bval,bindx] = max(startPop(:,xZomeLength)); %Best of current pop
best = startPop(bindx,:);
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
traceInfo(gen,4)=std(startPop(:,xZomeLength));
end
if ( (abs(bval - oval)>epsilon) | (gen==1)) %If we have a new best sol
if display
fprintf(1,'\n%d %f\n',gen,bval); %Update the display
end
if floatGA
bPop(bFoundIn,:)=[gen startPop(bindx,:)]; %Update bPop Matrix
else
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)
startPop(bindx,xZomeLength)];
end
bFoundIn=bFoundIn+1; %Update number of changes
oval=bval; %Update the best val
else
if display
fprintf(1,'%d ',gen); %Otherwise just update num gen
end
end
endPop = feval(selectFN,startPop,[gen selectOps]); %Select
if floatGA %Running with the model where the parameters are numbers of ops
for i=1:numXOvers,
for j=1:xOverOps(i,1),
a = round(rand(popSize-1)+1); %Pick a parent
b = round(rand(popSize-1)+1); %Pick another parent
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
[c1 c2] = feval(xN,endPop(a,:),endPop(b,:),bounds,[gen xOverOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar)) %Make sure we created a new
c1(xZomeLength)=endPop(a,xZomeLength); %solution before evaluating
elseif c1(1:numVar)==endPop(b,(1:numVar))
c1(xZomeLength)=endPop(b,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
if c2(1:numVar)==endPop(a,(1:numVar))
c2(xZomeLength)=endPop(a,xZomeLength);
elseif c2(1:numVar)==endPop(b,(1:numVar))
c2(xZomeLength)=endPop(b,xZomeLength);
else
%[c2(xZomeLength) c2] = feval(evalFN,c2,[gen evalOps]);
eval(e2str);
end
endPop(a,:)=c1;
endPop(b,:)=c2;
end
end
for i=1:numMuts,
for j=1:mutOps(i,1),
a = round(rand(popSize-1)+1);
c1 = feval(deblank(mutFNs(i,:)),endPop(a,:),bounds,[gen mutOps(i,:)]);
if c1(1:numVar)==endPop(a,(1:numVar))
c1(xZomeLength)=endPop(a,xZomeLength);
else
%[c1(xZomeLength) c1] = feval(evalFN,c1,[gen evalOps]);
eval(e1str);
end
endPop(a,:)=c1;
end
end
else %We are running a probabilistic model of genetic operators
for i=1:numXOvers,
xN=deblank(xOverFNs(i,:)); %Get the name of crossover function
cp=find(rand(popSize,1)<xOverOps(i,1)==1);
if rem(size(cp,1),2) cp=cp(1:(size(cp,1)-1)); end
cp=reshape(cp,size(cp,1)/2,2);
for j=1:size(cp,1)
a=cp(j,1); b=cp(j,2);
[endPop(a,:) endPop(b,:)] = feval(xN,endPop(a,:),endPop(b,:),
bounds,[gen xOverOps(i,:)]);
end
end
for i=1:numMuts
mN=deblank(mutFNs(i,:));
for j=1:popSize
endPop(j,:) = feval(mN,endPop(j,:),bounds,[gen mutOps(i,:)]);
eval(e1str);
end
end
end
gen=gen+1;
done=feval(termFN,[gen termOps],bPop,endPop); %See if the ga is done
startPop=endPop; %Swap the populations
[bval,bindx] = min(startPop(:,xZomeLength)); %Keep the best solution
startPop(bindx,:) = best; %replace it with the worst
end
[bval,bindx] = max(startPop(:,xZomeLength));
if display
fprintf(1,'\n%d %f\n',gen,bval);
end
x=startPop(bindx,:);
if opts(2)==0 %binary
x=b2f(x,bounds,bits);
bPop(bFoundIn,:)=[gen b2f(startPop(bindx,1:numVar),bounds,bits)
startPop(bindx,xZomeLength)];
else
bPop(bFoundIn,:)=[gen startPop(bindx,:)];
end
if collectTrace
traceInfo(gen,1)=gen; %current generation
traceInfo(gen,2)=startPop(bindx,xZomeLength); %Best fittness
traceInfo(gen,3)=mean(startPop(:,xZomeLength)); %Avg fittness
end
(1)关于fitness value,你要自己定义一个函数,如你所说从25个x变量经过一系列运算得到y值 可以其作为fitness value
(2)由于x的取值是离散的 染色体不一定要是二进制 最简单的做法是一个5进制的长为25的串。
% 主程序
%遗传算法主程序
%Name:genmainm
%author:杨幂
clear
clf
%%初始化
popsize=50; %群体大小
chromlength=30; %字符串长度(个体长度)
pc=06; %交叉概率
pm=01; %变异概率
pop=initpop(popsize,chromlength); %随机产生初始群体
%%开始迭代
for i=1:20 %20为迭代次数
[objvalue]=calobjvalue(pop); %计算目标函数
fitvalue=calfitvalue(objvalue); %计算群体中每个个体的适应度
[newpop]=selection(pop,fitvalue); %复制
[newpop]=crossover(pop,pc); %交叉
[newpop]=mutation(pop,pm); %变异
[bestindividual,bestfit]=best(pop,fitvalue); %求出群体中适应值最大的个体及其适应值
y(i)=max(bestfit);%储存最优个体适应值
n(i)=i;
pop5=bestindividual;%储存最优个体
%解码
x1(i)=decodechrom(pop5,1,chromlength/2)2/32767;
x2(i)=10+decodechrom(pop5,chromlength/2+1,chromlength/2)10/32767;
pop=newpop;%将新产生的种群作为当前种群
end
%%绘图
figure(1)%最优点变化趋势图
i=1:20;
plot(y(i),'-r')
xlabel('迭代次数');
ylabel('最优个体适应值');
title('最优点变化趋势');
legend('最优点');
grid on
figure(2)%最优点分布图
[X1,X2]=meshgrid(0:01:2,10:01:20);
Z=X1^2+X2^2;
mesh(X1,X2,Z);
xlabel('自变量x1'),ylabel('自变量x2'),zlabel('函数值f(x1,x2)');
hold on
plot3(x1,x2,y,'ro','MarkerEdgeColor','r','MarkerFaceColor','r','MarkerSize',5)
title('最优点分布');
legend('最优点');
hold off
[z index]=max(y); %计算最大值及其位置
x5=[x1(index),x2(index)]%计算最大值对应的x值
z
把下面的(1)-(7)依次存成相应的m文件,在(7)的m文件下运行就可以了
(1) 适应度函数fitm
function fitness=fit(len,m,maxlen,minlen)
fitness=len;
for i=1:length(len)
fitness(i,1)=(1-(len(i,1)-minlen)/(maxlen-minlen+00001))^m;
end
(2)个体距离计算函数 mylengthm
function len=myLength(D,p)
[N,NN]=size(D);
len=D(p(1,N),p(1,1));
for i=1:(N-1)
len=len+D(p(1,i),p(1,i+1));
end
end
(3)交叉 *** 作函数 crossm
function [A,B]=cross(A,B)
L=length(A);
if L<10
W=L;
elseif ((L/10)-floor(L/10))>=rand&&L>10
W=ceil(L/10)+8;
else
W=floor(L/10)+8;
end
p=unidrnd(L-W+1);
fprintf('p=%d ',p);
for i=1:W
x=find(A==B(1,p+i-1));
y=find(B==A(1,p+i-1));
[A(1,p+i-1),B(1,p+i-1)]=exchange(A(1,p+i-1),B(1,p+i-1));
[A(1,x),B(1,y)]=exchange(A(1,x),B(1,y));
end
end
(4)对调函数 exchangem
function [x,y]=exchange(x,y)
temp=x;
x=y;
y=temp;
end
(5)变异函数 Mutationm
function a=Mutation(A)
index1=0;index2=0;
nnper=randperm(size(A,2));
index1=nnper(1);
index2=nnper(2);
%fprintf('index1=%d ',index1);
%fprintf('index2=%d ',index2);
temp=0;
temp=A(index1);
A(index1)=A(index2);
A(index2)=temp;
a=A;
end
(6)连点画图函数 plot_routem
function plot_route(a,R)
scatter(a(:,1),a(:,2),'rx');
hold on;
plot([a(R(1),1),a(R(length(R)),1)],[a(R(1),2),a(R(length(R)),2)]);
hold on;
for i=2:length(R)
x0=a(R(i-1),1);
y0=a(R(i-1),2);
x1=a(R(i),1);
y1=a(R(i),2);
xx=[x0,x1];
yy=[y0,y1];
plot(xx,yy);
hold on;
end
end
(7)主函数
clear;
clc;
%%%%%%%%%%%%%%%输入参数%%%%%%%%
N=50; %%城市的个数
M=100; %%种群的个数
C=100; %%迭代次数
C_old=C;
m=2; %%适应值归一化淘汰加速指数
Pc=04; %%交叉概率
Pmutation=02; %%变异概率
%%生成城市的坐标
pos=randn(N,2);
%%生成城市之间距离矩阵
D=zeros(N,N);
for i=1:N
for j=i+1:N
dis=(pos(i,1)-pos(j,1))^2+(pos(i,2)-pos(j,2))^2;
D(i,j)=dis^(05);
D(j,i)=D(i,j);
end
end
%%如果城市之间的距离矩阵已知,可以在下面赋值给D,否则就随机生成
%%生成初始群体
popm=zeros(M,N);
for i=1:M
popm(i,:)=randperm(N);
end
%%随机选择一个种群
R=popm(1,:);
figure(1);
scatter(pos(:,1),pos(:,2),'rx');
axis([-3 3 -3 3]);
figure(2);
plot_route(pos,R); %%画出种群各城市之间的连线
axis([-3 3 -3 3]);
%%初始化种群及其适应函数
fitness=zeros(M,1);
len=zeros(M,1);
for i=1:M
len(i,1)=myLength(D,popm(i,:));
end
maxlen=max(len);
minlen=min(len);
fitness=fit(len,m,maxlen,minlen);
rr=find(len==minlen);
R=popm(rr(1,1),:);
for i=1:N
fprintf('%d ',R(i));
end
fprintf('\n');
fitness=fitness/sum(fitness);
distance_min=zeros(C+1,1); %%各次迭代的最小的种群的距离
while C>=0
fprintf('迭代第%d次\n',C);
%%选择 *** 作
nn=0;
for i=1:size(popm,1)
len_1(i,1)=myLength(D,popm(i,:));
jc=rand03;
for j=1:size(popm,1)
if fitness(j,1)>=jc
nn=nn+1;
popm_sel(nn,:)=popm(j,:);
break;
end
end
end
%%每次选择都保存最优的种群
popm_sel=popm_sel(1:nn,:);
[len_m len_index]=min(len_1);
popm_sel=[popm_sel;popm(len_index,:)];
%%交叉 *** 作
nnper=randperm(nn);
A=popm_sel(nnper(1),:);
B=popm_sel(nnper(2),:);
for i=1:nnPc
[A,B]=cross(A,B);
popm_sel(nnper(1),:)=A;
popm_sel(nnper(2),:)=B;
end
%%变异 *** 作
for i=1:nn
pick=rand;
while pick==0
pick=rand;
end
if pick<=Pmutation
popm_sel(i,:)=Mutation(popm_sel(i,:));
end
end
%%求适应度函数
NN=size(popm_sel,1);
len=zeros(NN,1);
for i=1:NN
len(i,1)=myLength(D,popm_sel(i,:));
end
maxlen=max(len);
minlen=min(len);
distance_min(C+1,1)=minlen;
fitness=fit(len,m,maxlen,minlen);
rr=find(len==minlen);
fprintf('minlen=%d\n',minlen);
R=popm_sel(rr(1,1),:);
for i=1:N
fprintf('%d ',R(i));
end
fprintf('\n');
popm=[];
popm=popm_sel;
C=C-1;
%pause(1);
end
figure(3)
plot_route(pos,R);
axis([-3 3 -3 3]);
以上就是关于怎么通过MATLAB使用遗传算法实现pid参数整定全部的内容,包括:怎么通过MATLAB使用遗传算法实现pid参数整定、运行遗基于遗传算法的BP神经网络MATLAB代码程序时总是出错!!!、遗传算法matlab程序最后目标函数值与自己的初始点所求得的值偏差太大等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)