while loop executes only once the embedded for loops

Hi everyone,
I'm working on a piece of code for the implementation of the Clarke-Wright constructive method for solving the Travelling Salesman Problem (TSP). The entire algorithm is on its place. The only issue is that it just executes the first iteration. See the while loop in the code below. It has the control variable 'TourSize' for looping. The code executes all the inner for loops once, and then it just decreases the control variable, according to the statement TourSize = TourSize - 1, and does not loop again in all the remaining for loops. I don't know what the problem is, and I even tried changing the while external loop by another for loop, with a given number of iterations, but the result is the same. Any help is mostly appreciated.
PD: Please ignore the comments in spanish.
if true
function Clarke_Wright
clc
fileID = fopen('berlin52tsp.txt'); %abre archivo y asigna un identificador (no soporta extensión .tsp)
M = readtable('berlin52tsp.txt','Delimiter',' '); %crea una tabla reconociendo los valores numéricos del archivo delimitados por espacios Var1=ciuidad, Var2=Coord X, Var3=Coord Y
MSize = size(M); %arroja el tamaño de la tabla en filas x columnas
NumberOfCities = MSize(1); %arroja el número de filas = número de ciudades del problema
A = M{1:NumberOfCities,{'Var2','Var3'}}; %Crea matriz con sólo las coordenadas X e Y de las ciudades
Dist = zeros(NumberOfCities); %Inicializa matriz de distancias
for i = 1:NumberOfCities
xPosSC = A(i,1); %Posición x de la ciudad i
yPosSC = A(i,2); %Posición y de la ciudad i
for j = 1:NumberOfCities
NextCity = j;
xPosNC = A(j,1); %Posición x de la ciudad j
yPosNC = A(j,2); %Posición y de la ciudad j
auxDistx = (xPosNC - xPosSC); %deltax entre ciudades i y j
auxDisty = (yPosNC - yPosSC); %deltay entre ciudades i y j
Dist(i,j) = sqrt(auxDistx^2 + auxDisty^2); %Matriz de distancias entre ciudades. Cada fila representa una ciudad, y sus columnas, las distancias con las demás ciudades
end
end
StartCity = 1; %Se elige cualquier ciudad como nodo central del tour
CurrentCity = StartCity; %Asignación de ciudad actualmente evaluada
Tour = StartCity; %Inicio de vector del tour
TotalDistance = 0; %Inicializa la distancia total de viaje del problema
VisitedCities = 0; %Inicializa contador de ciudades visitadas
%for i = 1:NumberOfCities
for i = 1:NumberOfCities
if i~=StartCity
auxpath = [i,StartCity];
Tour = [Tour,auxpath]; %Crea el tour cerrado que visita cada ciudad ida y vuelta desde el nodo central
end
end
for i = 1:NumberOfCities
if i~=StartCity
for j = 1:NumberOfCities
if (j~=StartCity) && (j~=i)
savings(i,j) = Dist(StartCity,i) + Dist(StartCity,j) - Dist(i,j); %Calcula ahorro de cambiar dos arcos de los nodos i,j al central, a un arco entre ellos
end
end
end
end
savings = triu(savings); %Transforma la matriz en triangular para evitar tomar el mismo ahorro dos veces
auxMax = 0;
%Aquí se inicia la secuencia de reemplazos de rutas al nodo origen por
%rutas adyacentes entre nodos con más ahorro de distancia
auxProc = size(Tour);
TourSize = auxProc(1,2);
while TourSize > NumberOfCities+1
%for n=1:1000
for i = 1:NumberOfCities
for j = 1:NumberOfCities
if savings(i,j) > auxMax
auxMax = savings(i,j); %Bucle condicional para extraer el máximo valor de la matriz de ahorros
coordx = i;
coordy = j;
end
end
end
savings(coordx,coordy) = 0; %Fija el máximo utilizado en 0 para evitar encontrarlo en una próxima iteración
auxpath=Tour;
auxSize = size(auxpath);
%hola =0;
for k = 1:auxSize(1,2)-1
if (Tour(1,k) == coordx) && (Tour(1,k+1) ~= coordy) %Este comparador doble garantiza que no se ponga una ruta entre dos nodos más de una vez
Tour(1,k+1) = coordy; %Modifica el vector path para poner los nodos coordx y coordy adyacentes en el tour
auxpos = k+1; %Marcador de posición del lugar de la modificación en el tour original
for m = auxpos:auxSize(1,2)-1
if auxpath(1,m) ~= coordy
Tour(1,m+1) = auxpath(1,m); %Continúa con el vector path original hasta llegar a la posición original del nodo coordy
else
Tour(m) = []; %Elimina el tour cerrado al nodo inicial que tenía el nodo coordy
end
end
end
end
%auxProc = size(path);
TourSize = TourSize-1;
%n = n + 1;
end
coordx
coordy
auxpath
Tour
end
end

댓글 수: 3

Please format your code properly using the "{} Code" button. The first part is not readable.
Jan
Jan 2018년 3월 8일
편집: Jan 2018년 3월 8일
@JOSE DE JESUS JARAMILLO SERNA: It would be more useful to edit the code in the original question instead of leaving the unreadable code there and posting a copy in a comment.
There is no reason to open the file by fopen, when you read it by readtable.
Redefining the important Matlab function path as a local variable is a bad idea. This can cause strange side-effects during debugging.
it just decreases the control variable, according to the statement
TourSize = TourSize - 1, and does not loop again in all the remaining
for loops. I don't know what the problem is, ...
You did not tell us yet, which problem you have. Do you get an error message or does the result differ from your expectations? For the latter case, what are your expectations? Does stepping through the code line by line using the debugger help to understand, what's going on internally?
Jan, thanks for your input. I didn't get any error messages, the problem is that I didn't get what it was supposed to give, there is only a 'while' loop in the entire code, and it contains several 'for' loops. The output should be a row vector which I called 'Tour' (previously 'path'), which should have been modified by the 'for' loops inside the 'while' loop, starting from an initial row vector. All these internal 'for' loops are executed correctly; however, they are supposed to run in every iteration of the 'while' loop, but this only occurs for the first iteration. For the remaining iterations, it only modifies the iteration control variable 'TourSize', which decreases by 1 in every iteration until the 'while' condition is not valid anymore. I just found out that, since I added the 'while' loop after I was doing some testing to the core algorithm, the initial value of variable 'auxMax', required to run the first 'for' cycle was left outside the 'while' loop. Thanks again for your input.

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

도움말 센터File Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by