Can someone explain to me what is happening here?

1 visualización (últimos 30 días)
Carolina Silva
Carolina Silva el 28 de Nov. de 2019
Comentada: dpb el 28 de Nov. de 2019
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 comentario
dpb
dpb el 28 de Nov. de 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.

Iniciar sesión para comentar.

Respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by