Travelling salesman problem - Dimension of arrays issue
2 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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)];
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!