Can someone explain to me what is happening here?

1 view (last 30 days)
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 Comment
dpb
dpb on 28 Nov 2019
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.

Sign in to comment.

Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!