Travelling salesman problem - Dimension of arrays issue

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

 채택된 답변

Torsten
Torsten 2023년 4월 3일
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

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

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

추가 답변 (0개)

제품

릴리스

R2023a

질문:

Vic
2023년 4월 3일

댓글:

Vic
2023년 4월 3일

Community Treasure Hunt

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

Start Hunting!

Translated by