Travelling salesman problem - Dimension of arrays issue

2 visualizaciones (últimos 30 días)
Vic
Vic el 3 de Abr. de 2023
Comentada: Vic el 3 de Abr. de 2023
Hi everyone,
I am trying to solve the travelling salesman problem by looking for the nearest point at each step.
My issue is the underlined script because it returns the following error:
"Error using horzcat
Dimensions of arrays being concatenated are not consistent."
Here is the code. I don't understand
----------------------------------------------------------------------------------
NStops = 5; %number of coordinates
Coordinates = zeros(NStops,3);
SortedCoordinates = zeros(NStops,3); %1st col will contain distance, 2nd & 3rd coordinates
%% Generation of coordinates
for i = 1:NStops
Coordinates(i,:)=[rand rand 0];
end
%% Determine the distances between the 1st value and all points in the Coordinates matrix
Min_Dist = [sqrt((Coordinates(:,1)-Coordinates(1,1)).^2+(Coordinates(:,2)-Coordinates(1,2)).^2) Coordinates(:,1) Coordinates(:,2)];
%%
for i = 1:NStops %for each
[~,rowInd] = min(Min_Dist(:,1)); %Select the shortest distance
SortedCoordinates(i,:) = Min_Dist(rowInd,:); %Copy the row in SortedCoordinates matrix in the right order
Min_Dist(rowInd,:)=[]; %Delete row already used in the SortedCoordinates matrix
Min_Dist = [sqrt((Min_Dist(:,2)-SortedCoordinates(i,2)).^2+(Min_Dist(:,3)-SortedCoordinates(i,3)).^2) Coordinates(:,1) Coordinates(:,2)]; %Recompute the shortest distance between the current listed in SortedCoordinates point and the remaining ones in Min_Dist
end
Thanks

Respuesta aceptada

Torsten
Torsten el 3 de Abr. de 2023
To concatenate the three vectors,
sqrt((Min_Dist(:,2)-SortedCoordinates(i,2)).^2+(Min_Dist(:,3)-SortedCoordinates(i,3)).^2)
Coordinates(:,1)
Coordinates(:,2)
all must have the same number of elements (rows). According to the error message, this is not the case.
Maybe you meant to concatenate them vertically, not horizontally:
Min_Dist = [sqrt((Min_Dist(:,2)-SortedCoordinates(i,2)).^2+(Min_Dist(:,3)-SortedCoordinates(i,3)).^2); Coordinates(:,1) ;Coordinates(:,2)];
  1 comentario
Vic
Vic el 3 de Abr. de 2023
Instead of using an entire matrix, I used a column.
Min_Dist(:,1) = sqrt((Min_Dist(:,2)-SortedCoordinates(i,2)).^2+(Min_Dist(:,3)-SortedCoordinates(i,3)).^2);
The solver works now.
Thanks for your reply

Iniciar sesión para comentar.

Más respuestas (0)

Productos


Versión

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by