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