Can someone explain to me what is happening here?
조회 수: 1 (최근 30일)
이전 댓글 표시
I want to calculate the total distance between an unknown number of cities that is within an array. For this I have to create a function that calculates this distance.
function [ route ] = pcv_stub( matDistance, source)
%matDistance is the matrix with the distances between each city.
rng(0)
n = length(matDistance);
route = source;
cities = 1:n;
cities = setdiff(cities, source);
while length(route) < n
city = randi(n);
if ~isempty(intersect(cities, city))
route = [route, city];
cities = setdiff(cities, city);
end
end
end
function total_distance = total_dist (route, matDistance)
%matDistance is matrix distance
vector_distance = [ ];
for i = 1:length (route) - 1
distance = matDistance (route(i), route(i+1));
vector_distance = [vector_distance, distance];
sum_distance = sum(vector_distance);
end
end
댓글 수: 1
dpb
2019년 11월 28일
So what's the question/problem?
The total_dist function is adding up the sums of all the preceding distances every time inside the loop may be the issue?
Move it (the sum) outside the loop or just keep a running sum since you aren't returning the vector you're building, anyways, there's no need for it.
답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!