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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by