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 CenterFile Exchange 中查找有关 Language Fundamentals 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by