• 大小: 5KB
    文件类型: .m
    金币: 1
    下载: 0 次
    发布日期: 2021-05-04
  • 语言: Matlab
  • 标签: hopfie  TSP  

资源简介

自己写的matlab代码 TSP,Hopfiled神经网络,代码功力不高见谅

资源截图

代码片段和文件信息

clear;clc;
% hopfield神经网络
% 问题拟定为在网格上随机选取N个点作为城市,然后计算出TSP问题的最优解
%(1)初始化Hopfield神经网络的初值
city_num=11;
% 惩罚参数A和D
% A=city_num^2;
% D=city_num/2;
A=1.5;
D=1;
%初始电压
u_0=0.02;
%步长
step=1;
%最大迭代次数
iter=0;
MAX=10000;
%最小能量最小距离
E_min=10000;
d_min=10000;
%(2)生成网格,并计算n个城市之间的距离矩阵Dxy
%随机生成城市坐标
% city_pos_1=randi([19]1city_num);
% city_pos_2=randperm(9);
city_perm=randperm(81);
city_perm=city_perm(11:city_num);
city_pos_1=(floor(city_perm./9)+1).*0.1;
city_pos_2=(mod(city_perm9)+1).*0.1;
city_pos=[city_pos_1;city_pos_2(11:city_num)];
% city_pos=[1122;1212];
% citys=load(‘8.txt‘);
%
% city_num=8;
% city_pos=citys‘;
%计算城市间距
d=zeros(city_num);
for i=1:city_num
    for j=1:city_num
        d(ij)=(city_pos(:i)-city_pos(:j))‘...
            *(city_pos(:i)-city_pos(:j));
        d(ij)=d(ij)^(1/2);
    end
end
%画出网格
hold on;
plot(city_pos(1:)city_pos(2:)‘Ko‘);
for k=1:city_num
    str=[‘   city‘ num2str(k) ‘‘];
    text(city_pos(1k)city_pos(2k)str);
end
% set(gca‘XLim‘[0 city_num+1]‘YLim‘[0 city_num+1]);
set(gca‘XLim‘[0 1]‘YLim‘[0 1]);
grid on;
%%
tic
%(3)初始化神经网络的输入状态
% U=zeros(city_num);
U_0=zeros(city_num)+u_0;
% delta=2*rand(city_num)-1;%随机项
delta=(2*rand(city_num)-1)/10;%随机项
U=(0.5*log(city_num-1)).*U_0+delta;
V=0.5*(1+tanh(U/u_0));

V_col=sum(V1);%列和
V_row=sum(V2);%行和
Best_Route=[E_min;d_min;zeros(city_num1)];
while iter~=MAX
    %(4)利用动态方程计算输入状态的增量,并更新神经网络下一个时刻的状态
    % 计算增量dU
%     if iter==0
%         U_c=U;
%     end  
    dU=zeros(city_num);
    for l=1:city_num
        for m=1:city_num
            m_0=m+1;
            m_1=m-1;
            if m==city_num
                m_0=1;
            end
            if m==1
                m_1=city_num;
            end
            dU(lm)=-A*(V_col(m)+V_row(l)-2)-...
                D*d(l:)*V(:m_0);
%             dU(lm)=-A*(V_row(m)-U(lm))-B*(V_col(l)-U(lm))-...
%                 C*(sum(V_row)-city_num)-D*(d(l:)*U(:m_0)+d(l:)*U(:m_1));
        end
    end
    %更新U
    U=U+dU*step;
    V=0.5*(1+tanh(U/u_0));
    %(5)计算当前的能量函数E
    V_col=sum(V1);%列和
    V_row=sum(V2);%行和
    part_1=sum((V_col-1).^2);
    part_2=sum((V_row-1).^2);
    part_3=0;
    for n=1:city_num
        for o=1:city_num
            for p=1:city_num
                p_0=p+1;
                if p==city_num
                    p_0=1;
                end
                part_3=part_3+V(np)*V(op_0)*d(no

评论

共有 条评论