Travelling salesman problem - Dimension of arrays issue

2 ビュー (過去 30 日間)
Vic
Vic 2023 年 4 月 3 日
コメント済み: Vic 2023 年 4 月 3 日
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 件のコメント
Vic
Vic 2023 年 4 月 3 日
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

Community Treasure Hunt

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

Start Hunting!

Translated by