Can someone explain to me what is happening here?

1 回表示 (過去 30 日間)
Carolina Silva
Carolina Silva 2019 年 11 月 28 日
コメント済み: dpb 2019 年 11 月 28 日
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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by