⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tsp1.m

📁 用遗传算法求解TSP(旅行商)问题
💻 M
字号:
function TSP(testDataSet,algorithmToUse)

close all;


defAlgrithm = 'SA'; % Simulated Annealing...
nPoint = 0;

if (nargin == 0)
    disp(sprintf('[%s]Please input the test data set and the algorithm used...',datestr(now)));
    return;
end % if...
if (nargin == 1)
    %disp(strcat('Default algorthm is selected as :',defAlgrithm,'...'));
    algorithmToUse = defAlgrithm;
end % if...

% reading data from both TSPLIB formatted and plain data set file...
% processing TSPLIB type...
infile = fopen(testDataSet,'r');
if (infile == -1)
    disp(sprintf('[%s]Test data set [%s] does not exist, program terminated. Bye...',datestr(now),testDataSet));
    return;
end % if...

% read the first line...
curLine = fgets(infile);
nLine = 0;
while(strncmp(curLine,'NODE_COORD_SECTION',18)==0 && nLine<9)
    curLine = fgets(infile);
    nLine = nLine + 1;
end % while...
% whether the type is TSPLIB?
if (strncmp(curLine,'NODE_COORD_SECTION',18) == 1)
    [T1,nPoint] = fscanf(infile,'%d %f %f',[3,inf]);
    fclose(infile);
    % only for speedup...
    ptCorr = T1(2:3,:)';
    nPoint = size(ptCorr,1);
    disp(sprintf('[%s]TSPLIB formatted test data set read complete...',datestr(now)));
% if plain data set file...
else
    ptCorr = load(testDataSet);
    nPoint = size(ptCorr,1);
    disp(sprintf('[%s]Plain data set file read complete...',datestr(now)));
end % if...


% select the optimization algorithm and run...
switch(algorithmToUse)
    case 'SA'
        disp(sprintf('[%s]The TSP problem would be solved by Simulated Annealing...',datestr(now)));
        TSP_SA(ptCorr,nPoint);
    case 'GA'
        disp(sprintf('[%s]The TSP problem would be solved by Genetic Algorithm...',datestr(now)));
        TSP_GA(ptCorr,nPoint);
    case 'PSO'
        disp(sprintf('[%s]The TSP problem would be solved by Particle Swarm Optimization...',datestr(now)));
        TSP_PSO(ptCorr,nPoint);
    case 'ACO'
        disp(sprintf('[%s]The TSP problem would be solved by Ant Colony Optimization...',datestr(now)));
        TSP_ACO(ptCorr,nPoint);        
    otherwise
        disp(sprintf('[%s]The TSP problem would be solved by Simulated Annealing...',datestr(now)));
        TSP_SA(ptCorr,nPoint);
end;

disp(' ');
disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
disp(sprintf('%% Traveling Salesman Problem using %s terminates successfully. Bye.',algorithmToUse));
disp('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%');
disp(' ');

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -