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 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Abhinav Sharma
am 17 Feb. 2021
Kommentiert: Abhinav Sharma
am 17 Feb. 2021
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);
0 Kommentare
Akzeptierte Antwort
dpb
am 17 Feb. 2021
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.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Language Fundamentals finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!