I am trying to find the shortest path possible in an array of numbers using MATLAB and I keep getting "Index in position 1 exceeds array bounds (must not exceed 5).". I tried changing 5 to any other number and it didn't work. Can anyone please help?

1 回表示 (過去 30 日間)
a = [1 4; 2 6; 3 8; 4 10; 5 12];
n = 1;
image(a);
disp(a);
iteration = 1;
iter = 1;
distanceShortest = 100;
chosenMatrix = [];
while iter < 50
itr = 1;
distance = 0;
randomA = a(randperm(size(a, 1)), :);
while itr < 5
distance = distance + norm([randomA(n,1) randomA(n,2)] - [randomA(n+1,1) randomA(n+1,2)]);
itr = itr + 1;
n = n + 1;
end
if distance < distanceShortest
distanceShortest = distance;
chosenMatrix = randomA;
end
iter = iter + 1;
end
disp(distanceShortest);
disp(chosenMatrix);

採用された回答

dpb
dpb 2021 年 2 月 17 日
Easy to forget/overlook...
n=1:
...
while itr < 5
distance = distance + norm([randomA(n,1) randomA(n,2)] - [randomA(n+1,1) randomA(n+1,2)]);
n=n+1;
...
You hold the loop iteration count to <5 (ought to use a variable here so can change size of A more easily, but that's a side issue) and reset itr inside the outer loop over iter, but you don't reset n Hence, it will be whatever it was at the end of the first inner loop and keep incrementing from there.

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLanguage Fundamentals についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by