|
连续Hopfield网络解决TSP(这个是matlab程序)- %连续Hopfield网络解决TSP
- function HopfieldTsp()
- clc;
- N=10; %城市数
- A=1.5; %系数A
- D=1; %系数D
- u0=0.02; %神经元函数斜率
- Step_t=0.1; %计算步长
- MaxEpochs=20000;%迭代次数
- %得到城市间距离矩阵
- CityCood=rand(2,N); %城市坐标
- DistanceMat=dist(CityCood',CityCood); %城市间距离矩阵
- U=0.2*rand(N,N)-0.1;%神经元输入初始值在0附近产生
- for Count=1:MaxEpochs
- V=(1+tansig(U/u0))/2;
- E=CacuEnergy(V,DistanceMat,A,D);%计算能量
- delta_U=CacuDeltaU(V,DistanceMat,A,D,Step_t);%计算U的增量
- U=U+delta_U*Step_t;
- end
- [NewV,CheckRes]=RouteCheck(V);%检查V是否是有效路径
- if(CheckRes<1)
- FinalE=CacuEnergy(NewV,DistanceMat,A,D);
- RouteLen=TotalRouteLength(NewV,CityCood);%计算路径的真实长度
- PlotRoute(NewV,CityCood);%绘制路径
- else
- disp('路径无效!!');
- end
- %能量计算
- function E=CacuEnergy(V,d,A,D)
- [n,n]=size(V);
- t1=sumsqr(sum(V,2)-1);
- t2=sumsqr(sum(V,1)-1);
- PermitV=V(:,2:n);
- PermitV=[PermitV V(:,1)];
- temp=d*PermitV;
- t3=sum(sum(V.*temp));
- E=0.5*(A*t1+A*t2+D+t3);
- %计算U的增量
- function d_U=CacuDeltaU(V,d,A,D,dt)
- [n,n]=size(V);
- t1=repmat(sum(V,2)-1,1,n);
- t2=repmat(sum(V,1)-1,n,1);
- PermitV=V(:,2:n);
- PermitV=[PermitV V(:,1)];
- t3=d*PermitV;
- d_U=-dt*(A*t1+A*t2+D*t3);
- %检查V是否是有效路径
- function [NewV,CheckRes]=RouteCheck(V)
- [rows,columns]=size(V);
- NewV=zeros(rows,columns);
- [XC,Order]=max(V);
- for j=1:columns
- NewV(Order(j),j)=1;
- end
- SC=sum(NewV);
- SR=sum(NewV');
- CheckRes=sumsqr(SC-SR);
- %绘制路径
- function PlotRoute(V,CityCood)
- figure;
- title('连续Hopfield网络解决TSP');
- xlabel('X坐标');
- ylabel('Y坐标');
- axis([0,1,0,1]);
- axis on;
- [xxx,order]=max(V);
- NewCood=CityCood(:,order);
- NewCood=[NewCood NewCood(:,1)];
- plot(NewCood(1,:),NewCood(2,:),'o-');
- %计算路径实际长度
- function Len=TotalRouteLength(V,CityCood)
- [xxx,order]=max(V);
- NewCood=CityCood(:,order);
- NewCood=[NewCood NewCood(:,1)];
- [rows,columns]=size(NewCood);
- Len=0;
- for i=2:columns
- Len=Len+dist(NewCood(:,i-1)',NewCood(:,i));
- end
复制代码
[ 本帖最后由 frogfish 于 2007-7-5 08:52 编辑 ] |
-
|