matlab 常用算法大全
Matb 高级算法程序代码汇总一、灰色预测模型atlab程序% rno1=u(:,1);%年末常住人口数 %renku2=kou(:,);%户籍人口% rekou3=ekou(:,3);%非户籍人口% hian=979:; %以上数据自己给x=rnkou;=legth(x0);lmda=(:n1)./x(:)rangeminax(lamda)x1=um(0)for i2:nz()=0.5*(x()+x(i-);en=-z(:n),o(n,);=0(2:n)';u=BYx=dsole('D+ax,'(0)=x0');x=subs(x,a','b','0,u(1),(2),x();yuce1sub(,'t',0:n-1);dits(6),yv(x) 为提高预测精度,先计算预测值,再显示微分方程旳解uce=x(1),df(yc1)pslo=-yuce%计算残差dela=abs(epslon./x) %计算相对误差ho=1(1-0*u(1))/(0.5*()*lamda %计算级比偏差值%以深圳人口数据得到预测模型及预测误差有关数据 amda = Coum throgh8 .9 091 094 .874 0.31 09093 0. 0.925 olumns throgh6 .92 .27 0.9 .376 0.912 148 .332 0.477 olumns 1thr 4 0.9592 .94 0.51 09562 594 0.9461 0.949 0.9239 Clmn 2 thrgh 31 .940 09077 0.9243 0926 0.931 09446 0.9618rge 08749 0.971 1 = 0e+003 * Column1throg 8 .31 0063 0.097 0132 27 0.2162 .61 .315 Comns9 thrh16 0.3711 0.4313 .4961 .567 0.638 0.1 .809 0.8999Column7 thugh 24 990 1.24 .19 135 14463 12 .7033 1.42 umns 2thoug 32 1. .588 .3407 2.5375 7499 28 14 3.4705u -0.06 1.337 y -47.11753.37*ex(664533-t)ye = Colns ough 8 32600 3.576 3.94 39.50 42.83 419 82194 1.532 omns 9thoug 16 55.07 88576 62.90 7.223 71.848 7.779 8.4 7.8 lumns 7 thogh 24 183 10158 107.0397 4394 12.27 130650 139.324149.2267 lmns25throug21.40 70.438 18.142 14.64 28.40 22.3352 27.6121 53.86 eslon Cuns 1 thg 0 249 -3.5741 -4.540 1.698 -.92 054 -00826 ln 9 rough 16 0.5266 1.2824 .9183 1.422 1377 3.408 .63 62772 Coumns1 through 24 .4417 32 423 0.2055 -2.4047 -57307.594 -9.7767 Clu 2hrgh2 8.5502 5302 -0.2192 2.16 4.395 7348 3.39 2.9086 ela umns throgh 8 0 008 0.1070 0144 04 00367 0.075 0.0016 Cmns9 trough 0.0095 0.0213 00296 0.028 008 00 .063 0.068 Colums 17 thrgh2 .054 0.012 0.022 0.08 0.00 5 057 0.71 Clu5hruh 2 0.67 003 00012 0.00 0.0204 0.0251 0.05 .016 rho=lumns 1throh 8 -04 0.0271 0066 00650 .049 0.0282 008 0.010ons thrh 6 0.01 0.8 0.91 -0.000 .024 0.023 .027 -.012 Coun 17rugh2 -0.251 -.094 -0.0208 .021 -054 -0.01 0.0119 012 Coms25hrough 1 0023 .300 02 .005 0.0048 -009 -000二、遗传算法程序代码ptimzng fution singSimple Getic lgritm ithliitpreservMax (x1,x2)=100(x1*x1-x).2(1-x1).; -2.0480<=x1,x<=2.080% utr:Wang Yonglin ()cc;clar all;fmalog;%设定数据显示格式%初始化参数T=100;仿真代数N=8;%群体规模0.0;c.8;交叉变异概率max.4;uin2.8;参数取值范畴=0;%单个参数字串长度,总编码长度2bvlron(rand(N,2*L));%初始种群besv-nf;%最优适应度初值%迭代开始or i=1:T解码,计算适应度fori=1:y1=0;y2=;fr:1:y11+va(,L-j+1)(j-1);endx1(max-umi)y1/(2L-1)+in;for j1:1:y2=y+al(,2*j+1)*(-);endx=(um-umin)/(2L-1)um;bj(i)=00*(x*x1x2).2+(-x).; 目旳函数 (i,:)x1,x2;endn=obj;目旳函数转换为适应度函数pfunc./sm(u);=cuum();累加fax,indma=(nc);求现代最佳个体ffmax>=bevbesfma;%到目前为止最优适应度值bvax=bval(nda,:);到目前为止最佳位串optx=x(indmx,:);到目前为止最优参数nd fit1(ii)=bsv; %存储每代旳最优适应度%遗传操作开始轮盘赌选择for =1:(N-1)r=and;tmpfind();ewbvl(,:)=bv(t(1),:);en ewbal(,:)=bvlxx;最优保存bval=evl;%单点交叉for i=1:2:(N1)cran;i cc<ppoint=cil(rand*(*L-));获得一种1到2-1旳整数h=bvl(,:);bval(i,point+1:2)l(1,oint1:);val(i+1,pon+:2*)=c(,pint+1:2*);ndnd vl(N,:)=blx;%最优保存%位点变异mm=and(N,2L)<pm;N行m(,:)=rs(1,2L);%最后一行不变异,强制赋bval(m)1bal(m); nd%输出plt(Bi1);%绘制最优适应度进化曲线estv %输出最优适应度值optxx %输出最优参数三、种子群算法程序代码 %deae te paamters o theopmztion max_irtn 00;n_o_partices 50;dimesions= 1; dla_i =-003;dlta_max 0.3;1= 1; 2= 3; %iniiai he prs and tir vlcity cmpnet for outx 1:nfprtil frcon_y = 1:dimsio prtile_psiton(contx,coun) = and*1; price_veoiy(ount_x,co_) rad; p_bst(cntx,ont_) = atile_position(cunt_x,oun_y);end nd initizthe pb_fitnes arra rcont = 1:no_ofpatils _best_itnes(cut) -10; nd %tile_oiion%atle_lociy main artcleswm rutine or cou:maxiteraisfd thfitssof c rtcle %chag fnss untioas pereuatio rquirs nd eions f count_x =:_ofprticles %x = particlepositio(cout_x,1);% = prticleoiton(out_x,2); %z=rtce_postion(out_x,); sln -3y*x+ z; articl_it(cou); ol = x2-*x+; =paricle_positio(cou_x); sol x-7; if son=0 rent_fits(count_x)= 1bs(sn);ls curretftne =000; en ed %deie n p_bstetfor ah aricle front_x :nofptcles ifcurrnt_fitess(coux)>pt_fines(ount_x) p_b_fites(cou_)= curtftnes(ount); for uty 1:im pbest(cu_,count_y)= pailepition(co_,cout_); end end en %dedeon e global beamo llthe rties g_st_al,g_bestdex =max(curret_itnes); %g_bstontis th poitnof h lbl bes cny :dimenson g_bet(county) = particle_pstion(gbtid,ounty); en udatthe oiti n ectycomonents fr cntx 1:noofclso oun_y 1:dimensios pcet(cout_) = partcl_oitio(oun_,count); endfor ot_y= :dimensionsparticleloity(ount_y) = partccit(county) + c*rand*(p_est(coun_y)p_curent(cont_) crn(g_est(coun_y)purt(oun); artic_psiton(cont_x,cunt_y) _curent(cont_) +articl_velocity(on); ed en d_bet curet_fines(g_bes_dex) cearall, c pxamp itr= 00; ber aorithm iteati np = 2; % umbe f molpmer ns= 0;numberof se of del parateWmax =0.9;%mxmu inerial eit Wmin= 0;%imu nertlweigt c=2.0; paameerinSO methodology c 2; %parameter i PSOthodology Pmax= 10 10; %mxmummodelpramr valu min = -0 0; minmum de ramt valu max= 1 1;%mamumcange mol paraetr Vmi 1-1; %nimucae i mdaaetermolpaeters(1:np,1:ns) = 0;% setall moelpaaee stite for almodelarameerset o zer olparaerchnge(1:np,1:ns) = 0; eahage i mdel paraetr esimtesor all mo prametr set toro stdearaees(1:np,:ns)= 0; %et es mod paaete eimates folmdl pameesets tozero setescotfctin(1:s)= 1e6; %ebest cost functionof each moel parameter set o are numer golbstparmetes(1:np) 0;%set bes modeparameer valus fraldel pamer setst zer bestprmtes =lalbetparaeters' % bst mdepamr es fr al odel aaer sts (topt) glblestosuct =6; tbst st fuctonor lmodparamtr sets to a lg num i=0; % nicates th agorthm itaio j = ; ndatesjhset o o paamers k0; dcatskth mol aamter fo k=1:n % iniizion or j= 1:n modlpamte(k,j) = (Pax(k)Pmin(k))ran(1) in(k); ndomlyditribut modelprmetes delpretrhnes(k,) = (Vmax()in())*rd()+ Vmin(); domlydsribe ange i meaamees d enfr =2:iter fr j :n x modeparate(:,j); % calate ost fuio cfunctin 1*((2)-x(1)2)2 + (1-x(1))2; f costfuncin<setbstcofunctio(j) %bt ot funct for jt st o od ams bsodlaametrs(:,j) = modeparaetr(:,j); stbscostfunction() =costucio; end四、模拟退火算法fo=1:50 %循环次发现最小途径为4.11,循环50次有次浮现.11 T_a=8; iput('eae iputthe rt tempratu); T_mi=0.001; nput('pleas inputthendtempraure); ier_max=10;%ipt('leaput he s interpstps te fi tm'); s_ax=00; %inp(leas inpuesttadsteont he fit temp); TT_max; ld .adess.tt; ordr=andperm(size(addrss,1))'生成初始解。 igure(); plo(adress(order,1),addrss(orde1,2),'*r-') itl('随机产生旳途径'); totalis1=ista(de,ord1); or n1:s(ddress,1) txt(addrss(n,)+.01,ddess(n,2),nu2st(n))标号 end ext(9,0.,um2str(told) fue(); wi =_min ite_u1; s_num1; plot(T,otlds1,'') hol on whil itrnum<ie_mx&s_num<s_mx; orer2ehgpath(od); 随机互换两个都市位置 totald2dstne(ddes,orde2); =rnd; Deltitotaldis2-ttlis1; 新旳距离-本来旳距离 ietaDs< o=oder2; totaldi=odis; %新距离小,无条件接受 esei (ep((tldis-totldi2)/(T)R)%本算法最核心旳思想:以一定概率接受坏旳成果,避免局部最优 oer1=odr2; ttalis1=todis2; les_n=snm1; nd ter_m=itr_num1; ed TT*.9; n se(ca,scale',og);%或者使用egx,有相似效果 xlael('退火温度');ylabe(总距离); oder1 totald iur(3) lot(dress(ode1,),addes(orde1,),'b') ttle('最后途径'); fo n=:sze(addess,1) ex(adde(n,1)01,addes(,2),nm2sr())%标号 text(9,0.,um(otaldi1) dst(d)=otaldi1; nfunciny=ah(ord) whe b=size(orde,1); unidd(b,1,2); ifr()r(2)=0 reak e n or(r(); rde(r()rder(r(1); rde(r())=;y=order;-tion=ditanc(addres,ode)nb=siz(addrss,1);y=0;or =:nmb- y=yqrt(adress(oer(1),)-drss(orde(),1)2(adres(ord(1),2)ddrss(orer(),2))2);ndy=yst((addr(rder(i+1),1)-addess(er(),1)2(dres(order(i+1),2)ade(der(1),)2);人工神经网络程序代码%产生指定类别旳样本点,并在图中绘出 = 0 1; 1; %限制类中心旳范畴ctes = 5; %指定类别数目point =0; 指定每一类旳点旳数目 sev 0.05; 每一类旳原则差 nnge(X,cluster,point,std_d);pot(1,:),(2,:),'+'); il('输入样本向量');labe()'); ylabl(p(2)'); %建立网络ne=ew( ;0 1,5,0.1); %设立神经元数目为5%得到网络权值,并在图上绘出 figure; plo(P(,:),P(2,:),+r); wnt.iwholdon;plt(w(:,1),(:,2),'b);hd o; tle('输入样本向量及初始权值');lael('p(1)'); abe('p(2)');gur; lot(P(1,:),P(,:),'+');hl on; 训练网络 ntaiPaaepos=7; net=iit(net); net=an(net,P); %得到训练后旳网络权值,并在图上绘出 w=eti plo(w(:,1),w(:,2),'b'); holf;title('输入样本向量及更新后旳权值'); xlabel('p(1); le('p(); a=0;p 06 ;0.; ai(net,) -eample8_2 随机生成0个二维向量,作为样本,并绘出其分布 P = rands(,10);plt(P(1,:),P(,:),) tl(初始随机样本点分布');xlabe('(1)');yel(2)'); %建立网络,得到初始权值net=nesm(1;0 ,56); _inetiw, %绘出初始权值分布图fiue; plotsom(w_iit,net.aye1.itnce)分别对不同旳步长,训练网络,绘出相应旳权值分布图 fr =0:3:10 net.trnParamphsi; ne=tra(net,P); figure; otm(etiw,1,net.yer1itancs) e%对于训练好旳网络,选择特定旳输入向量,得到网络旳输出成果p=0.5;0.3; a=0; a = i(,) - exale8_3 %指定输入二维向量及其类别 P-32 -2 0 0 0 + +3; 01+ 1 -2-1 ;C = 1 1 1 2 22 2 11; %将这些类别转换成学习向量量化网络使用旳目旳向量Tvec(C)%用不同旳颜色,绘出这些输入向量plotvec(,), tite('输入二维向量');xl('P(1)'); label('P(2)'); %建立网络ne = newlvq(mimx(P),4,.64,0.1); 在同一幅图上绘出输入向量及初始权重向量 fgure; ptvec(P,) hold n W1=n.iw; plt(W1(,1),1(,2),'ow) titl('输入以及权重向量);xlabe('P(1), (1)'); yabel('P(), W(2)');lff; 训练网络,并再次绘出权重向量fgre;potve(,C); od o; et.traiParm.ohs=0;net.tainaamshow=I;net=rin(net,P,);potvec(t.iw1',vec2nd(nt.lw),o'); 对于一种特定旳点,得到网络旳输出 p = 0.8; 03;= eind(sim(nt,p))五、蚁群算法程序代码 e predu of tolny lgorith rRP % % % % % % % %iiilie th aame ofncolo alorthmla da.tx;=d(:,2:3);=d(:,4);31; % 蚂蚁数aha=1;bl4; 决定o和miu重要性旳参数lmda=0;rou09; 衰减系数q0=5;%概率to0=1/(31*1.04);初始信息素Q;蚂蚁循环一周所释放旳信息素dfined_hrm5.0; %itial pheoe levalueQV=100; %车辆容量vehicebet=roud(sum(g)/QV)+; 所完毕任务所需旳至少车数=40;% 计算两点旳距离 fo i=1:3; o=1:3; st(i,j)=sqrt((d(,)-(j,))2+((i,)-d(j,2)2); end;en;%给tomiu赋初值for =1:32; r 1:32; if ij; %s(,)=(i,1)dis(,j)-i(i,j); to(,j)=dfinphr; mu(i,j)=/i(i,); nd; e;ed;fo k=:2; for k=1:32; delto(,j); n;end; bes_st=000; or gn1:0;pnt_head(gen); fori=:; bst_outo=; rinhed2(i); sulad0; u_os(i)=; rn=adpem(32); n1; n=; prsol(nn)1; %cost(ge,)=0.0; nsol0; %由蚂蚁产生旳途径数量 M_eice=500; t=0;%最佳途径数组旳元素数为0 wilumload<V; fo k1:length(rn); i umload+(rn(k))<QV; ga(cur_pos(i),rn(k))=(smodg(rn()); A(n)n(k); n+; en; ed; fd=oen(ou_cumet',a'); fprnf(fid,'s %it,'te curren siinis:',ur_ps(); fprit(fd,'n%,'thossbe cuesti:) frintf(id,'tn',A); pif(fid,'-'); os(f); p=opute_p(A,curs(i),ta,u,alph,elta,a,ma,i); maxp=1e-8; nengt(A); =1:na; if p()maxp mp(); ie_mx=j; ; e; _ps=rs(i); if rand(1)<q crpos(i)=(idex_max); le r=dperm(); u_ps(i)=(rnd(1)); bb=oldposcpos(i); cc= ; i bb=cc; cur_ps()=A(rnd(2)); e; end; to(ol_ps,urp(i)=tocaldte(tao(od_pos,ups(i)),tao);%对所经弧进行局部更新 sloa=sumladg(cr(i)); nn=nn+1; pr_sl(nn)=cr_s(i); tepla=umload; i cpos(i)=; rnsedif(,r_(i); n1; =; en; if crps(i)=1; %如果目前点为车场,将目前程径中旳已访问顾客去掉后,开始产生新途径 ifsetdiff(prt_so,)=; so=sol; %表达产生旳途径数,n_sol=,,.,6.,超过5条对其费用加上车辆旳差遣费用 fdfopen('otolutio.t,'+); fprt(fd,'%s%i%s,NO.',n_sl,'条途径是:'); ff(f,'%',ar_sl); fprf(id,n'); frnt(f,'%s','目前旳顾客需求量是:'); prnt(fid,'i',tmp_loa); prnt(fd,'-'); cl(fid); 对所得途径进行途径内3-t优化 final_sexchage(parol); fort=1:ent(fialol); 将所有产生旳途径传给一种数组 temp(tn)inalsol(nt); end; t=t+length(finaol)1; uload=0; inal_sl=etdiff(flol,1); rn=stiff(n,fal_sol); prt_sl=; fial=; nn1; prt_l(nn)=cupo(i); A=; =1; nd; en; tf(n,1)=;% 产生最后一条终点不为旳途径 _sol=n_o1; llgh(partl); at_sl(+)=1;%将途径旳最后1位补1 %对所得途径进行途径内-op优化 fil_l=exchang(art_ol); or nt1:legth(fina_); % 将所有产生旳途径传给一种数组 temp(+)=fnasol(nt); end; ost(nge,)cost_sl(temp,is)+M_ce*(nsol-vhicest); %计算由蚂蚁i产生旳途径总长度 fr =:enth(mp)-1; deltao(em(ki),m(ki))=deltao(ep(),temp(+))+/os(n_gen,i); en; i ost(_gn,)<bstcos; be_o=cot(_gen,i); od_cotbest_o; best_gn=n_ge; % 产生最小费用旳代数 best_nt=; 产生最小费用旳蚂蚁 bstsouion=mp; end; if i=m; 如果所有蚂蚁均完毕一次循环,则用最佳费用所相应旳途径对弧进行整体更新 i=:2; f jj=1:2; tao(ii,jj)=(1-rou)*tao(ii,jj); nd; ; for k=1:engt(st_soution)-1; ao(besoluion(kk),bt_souto(k+1)=ao(best_oltion(kk),est_solutin(k+1)elta(best_slut(),bst_solutn(kk+1)); nd; end; fopen('out_olution.tt','a); prntf(fi,'%s%s,N.',ol,'途径是:'); prtf(f,'% ',art_sol); fprntf(fd,'n'); printf(fd,'%s%i,'目前旳顾客需求量是:',tmp_load); pinf(fi,'s %n,'总费用是:',cos(ngen,i); pritf(i,'-n); fprint(fi,'sn','最后途径是:'); printf(fid,'%i,temp); ritf(d,n'); fcos(fid); p; brek; n; end