Selecting submatrix takes long

2 vues (au cours des 30 derniers jours)
Berlibur
Berlibur le 5 Jan 2019
Réponse apportée : Jan le 7 Jan 2019
I am working on a TSP tour construction algorithm, where distances are saved in a distance matrix D, and the tour is represented as a permutation of the n cities.
It starts with a partial tour of two nodes, and from then on it keeps adding an unvisited city until the partial tour contains all cities.
To decide which city to add to the current partial tour, I need a submatrix from the D distance matrix. However, this operation, as it turns out, takes about 90% of full running time. Is there any way to speed this up?
Here is part of my code: (the line that takes most time is the one that defines 'searchArea'
while numel(tour) < n-1
searchArea = D(nodesLeft,tour); %submatrix that needs to be investigated
addCity = findCity(searchArea); %find the city that should be added
addCity = nodesLeft(addCity); %convert 'addCity' from an idx to city number
tour = insertCity(D,tour,addCity); %insert city in partial tour appropriately
nodesLeft = nodesLeft(nodesLeft~=addCity);% update which cities are left over
end
EDIT:
nodesLeft is a shrinking vector containing all numbers not yet in tour.
similarly tour is a growing vector containing all numbers 1:n except for what is in nodesLeft
  2 commentaires
Walter Roberson
Walter Roberson le 6 Jan 2019
Are nodesLeft and tour numeric or logical?
My tests suggest that logical indexing is typically faster than numeric indexing, but that the timing for logical indexing can be pretty irregular.
Berlibur
Berlibur le 6 Jan 2019
numeric, I edited my question to clarify those.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 7 Jan 2019
The growing and shrinking of array is expensive, because Matlab has to allocate new arrays each time and copy the old contents (except for the deleted element). Usually it is cheaper to use arrays with constant sizes and a logical vector, which contain a true for cities, which are selected.
This might forward the creation of submatrices to the subfunctions, such that it depends on the implementation of the not shown functions like findCity. Without seeing the full code, it is hard to guess, if the "90%" can be avoided or to suggest working code.

Plus de réponses (0)

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by