下载
加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 智能优化算法程序代码集锦

智能优化算法程序代码集锦.doc

智能优化算法程序代码集锦

wu德宝wu
2019-02-16 0人阅读 举报 0 0 暂无简介

简介:本文档为《智能优化算法程序代码集锦doc》,可适用于高等教育领域

人工蚂蚁算法functionx,y,minvalue=AA(func)Examplex,y,minvalue=AA('Foxhole')clcticsubplot(,,)plotdraw(func)title(func,'Function')初始化各参数Ant=蚂蚁规模ECHO=迭代次数step=*rand()局部搜索时的步长temp=,各子区间长度start=end=start=end=Len=(endstart)AntLen=(endstart)AntP=初始化蚂蚁位置Fori=:AntX(i,)=(start(endstart)*rand())X(i,)=(start(endstart)*rand())func=AAFoxholeFunc(X(i,),X(i,))val=feval(func,X(i,),X(i,))T(i)=exp(val)初始信息素,随函数值大,信息素浓度小,反之亦然*********************************************************************end至此初始化完成ForEcho=:ECHO开始寻优P函数定义,P为全局转移选择因子a=b=(ECHO)**log()f=a*exp(b*Echo)a=b=(ECHO)**log()f=a*exp(b*Echo)ifEcho<=(ECHO)P=felseP=fendP函数定义,P为信息素蒸发系数a=b=(ECHO)*log()P=a*exp(b*Echo)lamda=()*rand()全局转移步长参数Wmax=()*rand()步长更新参数上限Wmin=()*rand()步长更新参数下限寻找初始最优值TBest=T()Forj=:AntifT(j)>=TBestTBest=T(j)BestIndex=jendendW=Wmax(WmaxWmin)*(EchoECHO)局部搜索步长更新参数Forjg=:Ant全局转移概率求取,当该蚂蚁随在位置不是bestindex时ifjg~=BestIndexr=T(BestIndex)T(jg)Prob(jg)=exp(r)exp(T(BestIndex))else当jg=BestIndex的时候进行局部搜索ifrand()<temp(,)=X(BestIndex,)W*steptemp(,)=X(Be(i)Gbest(i))<gradientovercertainlengthofepochs,terminaterun,default=eP()epochsbeforeerrorgradientcriterionterminatesrun,default=,iftheSSEdoesnotchangeoverepochsthenexitP()errorgoal,ifNaNthenunconstrainedminormax,default=NaNP()typeflag(whichkindofPSOtouse)=CommonPSOwintertia(default),=Treleatypes,=Clerc'sConstrictedPSO,Type"P()PSOseed,default==forinitialpositionsallrandom=forinitialparticlesasuserinputplotfcnoptionalnameofplottingfunction,default'goplotpso',makeyourownandputherePSOseedValueinitialparticleposition,dependsonP(),mustbesetifP()isor,notusedforP()=,needstobenXmwheren<=ps,andm<=DIfn<psandorm<DthenremainingvaluesaresetrandomonVarrangeOutputs:optOUToptimalinputsandassociatedminmaxoutputoffunction,ofform:bestinbestinbestinDbestOUTOptionalOutputs:trGbestateveryiteration,tracesflightofswARMteepochstotrain,returnedasavector:endepochExample:out=pso('Ackley')BrianBirgeRevfunctionOUT,varargout=PSO(functname,D,varargin)rand('state',sum(*clock))ifnargin<error('Notenougharguments')endPSOPARAMETERSifnargin==onlyspecifiedfunctnameandDD=VRmin=ones(D,)*VRmax=ones(D,)*VR=VRmin,VRmaxminmax=P=mv=plotfcn='goplotpso'elseifnargin==specifiedfunctname,D,andmvVRmin=ones(D,)*VRmax=ones(D,)*VR=VRmin,VRmaxminmax=mv=varargin{}ifisnan(mv)mv=endP=plotfcn='goplotpso'elseifnargin==specifiedfunctname,D,mv,Varrangemv=varargin{}ifisnan(mv)mv=endVR=varargin{}minmax=P=plotfcn='goplotpso'elseifnargin==Functname,D,mv,Varrange,andminmaxmv=varargin{}ifisnan(mv)mv=endVR=varargin{}minmax=varargin{}P=plotfcn='goplotpso'elseifnargin==Functname,D,mv,Varrange,minmax,andpsoparamsmv=varargin{}ifisnan(mv)mv=endVR=varargin{}minmax=varargin{}P=varargin{}psoparamsplotfcn='goplotpso'elseifnargin==Functname,D,mv,Varrange,minmax,andpsoparams,plotfcnmv=varargin{}ifisnan(mv)mv=endVR=varargin{}minmax=varargin{}P=varargin{}psoparamsplotfcn=varargin{}elseifnargin==Functname,D,mv,Varrange,minmax,andpsoparams,plotfcn,PSOseedValuemv=varargin{}ifisnan(mv)mv=endVR=varargin{}minmax=varargin{}P=varargin{}psoparamsplotfcn=varargin{}PSOseedValue=varargin{}elseerror('Wrong#ofinputarguments')endsetsupdefaultpsoparamsPdef=eNaNPlen=length(P)P=P,Pdef(Plen:end)df=P()me=P()ps=P()ac=P()ac=P()iw=P()iw=P()iwe=P()ergrd=P()ergrdep=P()errgoal=P()trelea=P()PSOseed=P()usedwithtrainpso,Forneuralnettrainingifstrcmp(functname,'psoneteval')net=evalin('caller','net')Pd=evalin('caller','Pd')Tl=evalin('caller','Tl')Ai=evalin('caller','Ai')Q=evalin('caller','Q')TS=evalin('caller','TS')enderrorcheckingif((minmax==)isnan(errgoal))error('minmax=,errgoal=NaN:chooseanerrorgoalorsetminmaxtoor')endif((PSOseed==)~exist('PSOseedValue'))error('PSOseedflagsetbutnoPSOseedValuewasinput')endifexist('PSOseedValue')tmpsz=size(PSOseedValue)ifD<tmpsz()error('PSOseedValuecolumnsizemustbeDorless')endifps<tmpsz()error('PSOseedValuerowlengthmustbe#ofparticlesorless')endendsetplottingflagif(P())~=plotflg=elseplotflg=endpreallocatevariablesForspeeduptr=ones(,me)*NaNtakecareofsettingmaxvelocityandpositionparamshereiflength(mv)==velmaskmin=mv*ones(ps,D)minvel,psXDmatrixvelmaskmax=mv*ones(ps,D)maxvelelseiflength(mv)==Dvelmaskmin=repmat(Forcerow(mv),ps,)minvelvelmaskmax=repmat(Forcerow(mv),ps,)maxvelelseerror('MaxvelmustbeeitherascalarorsamelengthasprobdimensionD')endposmaskmin=repmat(VR(:D,)',ps,)minpos,psXDmatrixposmaskmax=repmat(VR(:D,)',ps,)maxposposmaskmeth==bouncemethod(seecommentsbelowinsideepochloop)PLOTTINGmessage=sprintf('PSO:ggiterations,GBest=gn',me)INITIALIZEINITIALIZEINITIALIZEINITIALIZEINITIALIZEINITIALIZEinitializepopulationofparticlesandtheirvelocitiesattimezero,formatofpos=(particle#,dimension)constructrandompopulationpositionsboundedbyVRpos(:ps,:D)=normmat(rand(ps,D),VR',)ifPSOseed==initialpositionsuserinput,seecommentsabovetmpsz=size(PSOseedValue)pos(:tmpsz(),:tmpsz())=PSOseedValueendconstructinitialrandomvelocitiesbetweenmv,mvvel(:ps,:D)=normmat(rand(ps,D),forcecol(mv),forcecol(mv)',)initialpbestpositionsvalspbest=posVECTORIZETHIS,oratleastvectorizecostfunctcallout=feval(functname,pos)returnscolumnofcostvalues(foreachparticle)pbestval=outinitially,pbestissameasposassigninitialgbestherealso(gbestandgbestval)ifminmax==thispicksgbestvalwhenwewanttomaximizethefunctiongbestval,idx=max(pbestval)elseifminmax==thisworksforstraightminimizationgbestval,idx=min(pbestval)elseifminmax==thisworkswhenyouknowtargetbutnotdirectionyouneedtogogoodforacostfunctionthatreturnsdistancetotargetthatcanbeeithernegativeorpositive(directioninfo)temp,idx=min((pbestvalones(size(pbestval))*errgoal)^)gbestval=pbestval(idx)endpreallocateavariabletokeeptrackofgbestforallitersbestpos=zeros(me,D)*NaNgbest=pbest(idx,:)thisisgbestpositionusedwithtrainpso,Forneuralnettrainingassigngbesttonetateachiteration,theseinterimassignmentsareForplottingmostlyifstrcmp(functname,'psoneteval')net=setx(net,gbest)endtr()=gbestvalsaveForoutputbestpos(,:D)=gbestthispartusedforimplementingCarlisleandDozier'sAPSOideaslightlymodified,thistrackstheglobalbestasthesentrywhereastheir'schoosesadifferentpointtoactassentrysee"TrackingChangingExtremeawithAdaptiveParticleSwARMOptimizer",partoftheWACProceedings,June,sentryval=gbestvalsentry=gbestif(trelea==)calculateClerc'sconstrictioncoefficientchitouseinhisformkappa=standardval=,changeformoreorlessconstrictionif((acac)<=)chi=kappaelsepsi=acacchiden=abs(psisqrt(psi^*psi))chinum=*kappachi=chinumchidenendendINITIALIZEENDINITIALIZEENDINITIALIZEENDINITIALIZEENDrstflg=fordynamicenvironmentcheckingstartPSOiterativeprocedurescnt=counterusedforupdatingdisplayaccordingtodfintheoptionscnt=counterusedforthestoppingsubroutinebasedonerrorconvergenceiwt()=iwfori=:mestartepochloop(iterations)out=feval(functname,posgbest)outbestval=out(end,:)out=out(:end,:)tr(i)=gbestvalkeeptrackofglobalbestvalte=ireturnsepochnumbertocallingprogramwhendonebestpos(i,:D)=gbest,gbestvalassignin('base','bestpos',bestpos(i,:D))thissectiondoestheplotsduringiterationsifplotflg==if(rem(i,df)==)|(i==me)|(i==)fprintf(message,i,gbestval)cnt=cntcounthowmanytimeswedisplay(usefulformovies)eval(plotfcn)definedattopofscriptendendupdatedisplayeverydfifstatementendendplotflgifstatementcheckforanerrorspacethatchangeswrttimeiterthresholdvaluethatdeterminesdynamicenvironmentseesifthevalueofgbestchangesmorethansomethresholdvalueforthesamelocationchkdyn=rstflg=fordynamicenvironmentcheckingifchkdyn==threshld=percentcurrentbestisallowedtochange,=etcletiter=#ofiterationsbeforecheckingenvironment,leaveatleastsoPSOhastimetoconvergeoutorng=abs((outbestvalgbestval))>=threshldsamepos=(max(sentry==gbest))if(outorngsamepos)rem(i,letiter)==rstflg=disp('NewEnvironment:resetpbest,gbest,andvel')resetpbestandpbestvalifwarrantedoutpbestval=feval(functname,pbest)Poutorng=abs((outpbestvalpbestval))>threshldpbestval=pbestval*~Poutorngoutpbestval*Poutorngpbest=pbest*repmat(~Poutorng,,D)pos*repmat(Poutorng,,D)pbest=posresetpersonalbeststocurrentpositionspbestval=outvel=vel*agitateparticlesalittle(oralot)recalculatebestvalsifminmax==gbestval,idx=max(pbestval)elseifminmax==gbestval,idx=min(pbestval)elseifminmax==thissectionneedsworktemp,idx=min((pbestvalones(size(pbestval))*errgoal)^)gbestval=pbestval(idx)endgbest=pbest(idx,:)usedwithtrainpso,Forneuralnettrainingassigngbesttonetateachiteration,theseinterimassignmentsareForplottingmostlyifstrcmp(functname,'psoneteval')net=setx(net,gbest)endendendifoutorngsentryval=gbestvalsentry=gbestendendifchkdynfindparticleswherewehavenewpbest,dependingonminmaxchoicethenfindgbestandgbestvalsize(out),size(pbestval)ifrstflg==ifminmax==tempi=find(pbestval>=out)newminpbestvalspbestval(tempi,)=out(tempi)updatepbestvalspbest(tempi,:)=pos(tempi,:)updatepbestpositionsiterbestval,idx=min(pbestval)ifgbestval>=iterbestvalgbestval=iterbestvalgbest=pbest(idx,:)usedwithtrainpso,Forneuralnettrainingassigngbesttonetateachiteration,theseinterimassignmentsareforplottingmostlyifstrcmp(functname,'psoneteval')net=setx(net,gbest)endendelseifminmax==tempi,dum=find(pbestval<=out)newmaxpbestvalspbestval(tempi,)=out(tempi,)updatepbestvalspbest(tempi,:)=pos(tempi,:)updatepbestpositionsiterbestval,idx=max(pbestval)ifgbestval<=iterbestvalgbestval=iterbestvalgbest=pbest(idx,:)usedwithtrainpso,forneuralnettrainingassigngbesttonetateachiteration,theseinterimassignmentsareforplottingmostlyifstrcmp(functname,'psoneteval')net=setx(net,gbest)endendelseifminmax==thiswon'tworkasitis,fixitlateregones=errgoal*ones(ps,)vectoroferrgoalssqrerr=((pbestvalegones)^)sqrerr=((outegones)^)tempi,dum=find(sqerr<=sqrerr)findparticlesclosesttotargpbestval(tempi,)=out(tempi,)updatepbestvalspbest(tempi,:)=pos(tempi,:)updatepbestpositionssqrerr=((pbestvalegones)^)needtodothistoreflectnewpbeststemp,idx=min(sqrerr)iterbestval=pbestval(idx)if(iterbestvalerrgoal)^<=(gbestvalerrgoal)^gbestval=iterbestvalgbest=pbest(idx,:)usedwithtrainpso,forneuralnettrainingassigngbesttonetateachiteration,theseinterimassignmentsareforplottingmostlyifstrcmp(functname,'psoneteval')net=setx(net,gbest)endendendendbuildasimplepredictorthorder,forgbesttrajectoryifi>fordimcnt=:Dpredcoef=polyfit(i:i,(bestpos(i:i,dimcnt))',)predcoef=polyfit(:i,(bestpos(:i,dimcnt))',)gbestpred(i,dimcnt)=polyval(predcoef,i)endelsegbestpred(i,:)=zeros(size(gbest))endgbestpred(i,:)=gbestassignin('base','gbestpred',gbestpred)converttononinertialframegbestoffset=gbestgbestpred(i,:)gbest=gbestgbestoffsetpos=posrepmat(gbestoffset,ps,)pbest=pbestrepmat(gbestoffset,ps,)PSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOgetnewvelocities,positions(thisistheheartofthePSOalgorithm)eachepochgetnewsetofrandomnumbersrannum=rand(ps,D)ForTreleaandClerctypesrannum=rand(ps,D)iftrelea==fromTrelea'spaper,parametersetvel=*velprevvel*rannum*(pbestpos)independent*rannum*(repmat(gbest,ps,)pos)socialelseiftrelea==fromTrelea'spaper,parametersetvel=*velprevvel*rannum*(pbestpos)independent*rannum*(repmat(gbest,ps,)pos)socialelseiftrelea==Clerc'sType"PSOvel=chi*(velprevvelac*rannum*(pbestpos)independentac*rannum*(repmat(gbest,ps,)pos))socialelsecommonPSOalgowithinertiawtgetinertiaweight,justalinearfunctwrtepochparameteriweifi<=iweiwt(i)=((iwiw)(iwe))*(i)iwelseiwt(i)=iwendrandomnumberincludingaccelerationconstantsac=rannum*acForcommonPSOwinertiaac=rannum*acvel=iwt(i)*velprevvelac*(pbestpos)independentac*(repmat(gbest,ps,)pos)socialendlimitvelocitieshereusingmaskingvel=((vel<=velmaskmin)*velmaskmin)((vel>velmaskmin)*vel)vel=((vel>=velmaskmax)*velmaskmax)((vel<velmaskmax)*vel)updatenewposition(PSOalgo)pos=posvelpositionmasking,limitspositionstodesiredsearchspacemethod:)nopositionlimiting,)saturationatlimit,)wraparoundatlimit,)bounceofflimitminposmaskthrowaway=pos<=posmaskminthesearepsXDmatricesminposmaskkeep=pos>posmaskminmaxposmaskthrowaway=pos>=posmaskmaxmaxposmaskkeep=pos<posmaskmaxifposmaskmeth==thisisthesaturationmethodpos=(minposmaskthrowaway*posmaskmin)(minposmaskkeep*pos)pos=(maxposmaskthrowaway*posmaskmax)(maxposmaskkeep*pos)elseifposmaskmeth==thisisthewraparoundmethodpos=(minposmaskthrowaway*posmaskmax)(minposmaskkeep*pos)pos=(maxposmaskthrowaway*posmaskmin)(maxposmaskkeep*pos)elseifposmaskmeth==thisisthebouncemethod,particlesbounceofftheboundarieswithvelpos=(minposmaskthrowaway*posmaskmin)(minposmaskkeep*pos)pos=(maxposmaskthrowaway*posmaskmax)(maxposmaskkeep*pos)vel=(vel*minposmaskkeep)(vel*minposmaskthrowaway)vel=(vel*maxposmaskkeep)(vel*maxposmaskthrowaway)elsenochange,thisistheoriginalEberhart,Kennedymethod,itletstheparticlesgrowbeyondboundsifpsoparams(P)especiallyVmax,aren'tsetcorrectly,seetheliteratureendPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOPSOcheckForstoppingcriterionbasedonspeedofconvergencetodesirederrortmp=abs(tr(i)gbestval)iftmp>ergrdcnt=elseiftmp<=ergrdcnt=cntifcnt>=ergrdepifplotflg==fprintf(message,i,gbestval)disp('')disp('>Solutionlikely,GBesthasn''tchangedbyatleast',numstr(ergrd),'For',numstr(cnt),'epochs')eval(plotfcn)endbreakendendthisstopsifusingconstrainedoptimizationandgoalisreachedif~isnan(errgoal)if((gbestval<=errgoal)(minmax==))|((gbestval>=errgoal)(minmax==))ifplotflg==fprintf(message,i,gbestval)disp('')disp('>ErrorGoalreached,successfultermination!')eval(plotfcn)endbreakendthisisstoppingcriterionforconstrainedfrombothsidesifminmax==if((tr(i)<errgoal)(gbestval>=errgoal))|((tr(i)>errgoal)(gbestval<=errgoal))ifplotflg==fprintf(message,i,gbestval)disp('')disp('>ErrorGoalreached,successfultermination!')eval(plotfcn)endbreakendendendifminmax==endend~isnanifconvertbacktoinertialframepos=posrepmat(gbestoffset,ps,)pbest=pbestrepmat(gbestoffset,ps,)gbest=gbestgbestoffsetendendepochloopcleartempoutputsevalin('base','cleartemppsoouttemptetemptr')outputreturnOUT=gbest'gbestvalvarargout{}=:tevarargout{}=tr(find(~isnan(tr)))returnforcecolmfunctiontoforceavectortobeasinglecolumnBrianBirgeRevfunctionout=forcecol(in)len=prod(size(in))out=reshape(in,len,)goplotpsomdefaultplottingscriptusedinPSOfunctionsthisscriptisnotafunction,itisapluginforthemainPSOroutine(psoTreleavectorized)soitsharesallthesamevariables,becarefulwithvariablenameswhenmakingyourownpluginBrianBirgeRevsetupfigure,changethisForyourownmachineclfset(gcf,'Position',)thisisthecomputerdependentpartset(gcf,'Position',)set(gcf,'Doublebuffer','on')particleplot,upperrightsubplot('position',,,,)set(gcf,'color','k')plot(pos(:,),pos(:,D),out,'b','Markersize',)holdonplot(pbest(:,),pbest(:,D),pbestval,'g','Markersize',)plot(gbest(),gbest(D),gbestval,'r','Markersize',)crosshairsoffx=max(abs(min(min(pbest(:,)),min(pos(:,)))),abs(max(max(pbest(:,)),max(pos(:,)))))offy=max(abs(min(min(pbest(:,D)),min(pos(:,D)))),abs(min(max(pbest(:,D)),max(pos(:,D)))))plot(gbest()offxgbest()offx,gbest(D)gbest(D),gbestvalgbestval,'r')plot(gbest()gbest(),gbest(D)offygbest(D)offy,gbestvalgbestval,'r')holdoffxlabel('Dimension','color','y')ylabel('Dimension',numstr(D),'color','y')zlabel('Cost','color','y')title('ParticleDynamics','color','w','fontweight','bold')set(gca,'Xcolor','y')set(gca,'Ycolor','y')set(gca,'Zcolor','y')set(gca,'color','k')cameracontrolview()tryaxis(gbest()offx,gbest()offx,gbest(D)offy,gbest(D)offy)catchaxis(VR(,),VR(,),VR(D,),VR(D,))enderrorplot,leftsidesubplot('position',,,,)semilogy(tr(find(~isnan(tr))),'color','m','linewidth',)plot(tr(find(~isnan(tr))),'color','m','linewidth',)xlabel('epoch','color','y')ylabel('gbestval','color','y')ifD==titstr=sprintf('g=s(g)',gbestval,strrep(functname,'',''),gbest())elseifD==titstr=sprintf('g=s(g,g)',gbestval,strrep(functname,'',''),gbest(),gbest())elseifD==titstr=sprintf('g=s(g,g,g)',gbestval,strrep(functname,'',''),gbest(),gbest(),gbest())elsetitstr=sprintf('g=s(ginputs)',gbestval,strrep(functname,'',''),D)endtitle(titstr,'color','m','fontweight','bold')gridonaxistightset(gca,'Xcolor','y')set(gca,'Ycolor','y')set(gca,'Zcolor','y')set(gca,'color','k')set(gca,'YMinorGrid','off')textboxinlowerrightdoingitthiswaysoIcanFormateachlineanywayIwantsubplot('position',,,,)cleartitstriftrelea==PSOtype='CommonPSO'xtraname='InertiaWeight:'xtraval=numstr(iwt(length(iwt)))elseiftrelea==|trelea==PSOtype=('TreleaType',numstr(trelea))xtraname=''xtraval=''elseiftrelea==PSOtype=('ClercType"')xtraname='chivalue:'xtraval=numstr(chi)endifisnan(errgoal)errgoalstr='Unconstrained'elseerrgoalstr=numstr(errgoal)endifminmax==minmaxstr='Maximizeto:'elseifminmax==minmaxstr='Minimizeto:'elseminmaxstr='Targetto:'endifrstflg==rststat='EnvironmentChange'rststat=''elserststat=''rststat=''endtitstr={'PSOModel:',PSOtype'Dimensions:',numstr(D)'#ofparticles:',numstr(ps)minmaxstr,errgoalstr'Function:',strrep(functname,'','')xtraname,xtravalrststat,rststat}text(,,titstr{,},titstr{,},'color','g','fontweight','bold')holdontext(,,titstr{,},titstr{,},'color','m')text(,,titstr{,},titstr{,},'color','m')text(,,titstr{,},'color','w')text(,,titstr{,},'color','m')text(,,titstr{,},titstr{,},'color','m')text(,,titstr{,},titstr{,},'color','w','fontweight','bold')text(,,titstr{,},titstr{,},'color','r','fontweight','bold')ifwearetraininganeuralnet,showafewmoreparametersifstrcmp('psoneteval',functname)netispassedfromtrainpsotopsoTreleavectorizedincaseyouarewonderingwherethatstructurecomesfromhiddlyrstr=Forlyrcnt=:length(netlayers)TF{lyrcnt}=netlayers{lyrcnt}transferFcnSn(lyrcnt)=netlayers{lyrcnt}dimensionshiddlyrstr=hiddlyrstr,',',TF{lyrcnt}endhiddlyrstr=hiddlyrstr(:end)text(,,'#neurlyr=',numstr(netinputs{}size),'',numstr(Sn),'','color','c','fontweight','normal','fontsize',)text(,,'LyrFcn:',hiddlyrstr,'color','c','fontweight','normal','fontsize',)endlegstr={'Green=PersonalBests''Blue=CurrentPositions''Red=GlobalBest'}text(,,legstr{},'color','g')text(,,legstr{},'color','b')text(,,legstr{},'color','r')holdoffset(gca,'color','k')set(gca,'visible','off')drawnowfunctionout,varargout=normmat(x,newminmax,flag)normmatmtakesamatrixandreFormatsthedatatofitbetweenanewrangeUsage:xprime,mins,maxs=normmat(x,range,method)Inputs:xmatrixtoreFormatofdimensionMxNrangeavectorormatrixspecifyingminimumandmaximumvaluesForthenewmatrixformethod=,rangeisaelementrowvectorofmin,maxformethod=,rangeisarowmatrixwithsamecolumnsizeasinputmatrixwithformatofmin,min,minNmax,max,maxMformethod=,rangeisacolumnmatrixwithsamerowsizeasinputmatrixwithformatofmin,maxmin,max,minM,maxMalternativelyformethodand,caninputjustaelementvectorasinmethodthiswilljustapplythesameminmaxacrosseachcolumnorrowrespectivelymethodascalarflagwiththefollowingfunction=,normalizeeachcolumnoftheinputmatrixseparately=,normalizeeachrowoftheinputmatrixseparately=,normalizematrixgloballyOutputs:xprimenewmatrixnormalizedpermethodmins,maxsoptionaloutputsreturntheminandmaxvectorsoftheoriginalmatrixxusedforrecoveringoriginalmatrixfromxprimeexample:x=,,,,,,xprime,mins,maxs=normmat(x,,,)BrianBirgeRevchangednameoffunctiontoavoidsamenameinrobustcontroltoolboxifflag==a=min(min((x)))b=max(max((x)))ifabs(a)>abs(b)large=asmall=belselarge=bsmall=aendtemp=size(newminmax)iftemp()~=error('Error:formethod=,rangevectormustbeaelementrowvector')endden=abs(largesmall)range=newminmax()newminmax()ifden==out=xelsez=(xa)(den)out=z*rangenewminmax()*ones(size(z))endelseifflag==a=min(x,,)b=max(x,,)fori=:length(b)ifabs(a(i))>abs(b(i))large(i)=a(i)small(i)=b(i)elselarge(i)=b(i)small(i)=a(i)endendden=abs(largesmall)temp=size(newminmax)iftemp()*temp()==newminmaxA(,:)=newminmax()*ones(size(x(,:)))newminmaxA(,:)=newminmax()*ones(size(x(,:)))elseiftemp()>error('Error:formethod=,rangematrixmusthaverowsandsamecolumnsasinputmatrix')elsenewminmaxA=newminmaxendrange=newminmaxA(,:)newminmaxA(,:)forj=:length(x(:,))fori=:length(b)ifden(i)==out(j,i)=x(j,i)elsez(j,i)=(x(j,i)a(i))(den(i))out(j,i)=z(j,i)*range(,i)newminmaxA(,i)endendendelseifflag==a=min(x,,)b=max(x,,)Fori=:length(b)ifabs(a(i))>abs(b(i))large(i)=a(i)small(i)=b(i)elselarge(i)=b(i)small(i)=a(i)endendden=abs(largesmall)temp=size(newminmax)iftemp()*temp()==newminmaxA(:,)=newminmax()*ones(size(x(:,)))newminmaxA(:,)=newminmax()*ones(size(x(:,)))elseiftemp()>error('Error:formethod=,rangematrixmusthavecolumnsandsamerowsasinputmatrix')elsenewminmaxA=newminmaxendrange=newminmaxA(:,)newminmaxA(:,)forj=:length(x(,:))fori=:length(b)ifden(i)==out(i,j)=x(i,j)elsez(i,j)=(x(i,j)a(i))(forcecol(den(i)))out(i,j)=z(i,j)*range(i,)newminmaxA(i,)endendendendvarargout{}=avarargout{}=bretur

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

文档小程序码

使用微信“扫一扫”扫码寻找文档

1

打开微信

2

扫描小程序码

3

发布寻找信息

4

等待寻找结果

我知道了
评分:

/166

智能优化算法程序代码集锦

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利