How to remove duplicate nodes and those inbetween from an array of elements?

2 次查看(过去 30 天)
I really need help on this. Been at it for a week.
I have a randomly generated path between nodes 1 to 25.
Initial generation: 1 6 7 2 1 6 7 8 9 4 3 2 1 6 7 12 11 16 21 22 23 24 19 20 25
I want to remove all repeated segments and nodes so based on this, the final path I want is:
(1, 6, 7, 12, 11, 16, 21, 22, 23, 24, 19, 20, 25)
How should I do this? Pls help.
A user helped me reduce this with the following code:
while true
pathhist = histcounts(path, [unique(path), Inf]);
duplicate = path(find(pathhist > 1, 1)); %find identical digit
if isempty(duplicate)
break; %nothing left to remove, exit loop
end
occurences = path == duplicate;
path(find(occurences, 1) : find(occurences, 1, 'last')-1) = []; %delete 1st occurence and anything up to last occurence
end
However, my paths generated may have up to 500 elements and the code doesnt seem to be able to handle it.
Help is really, really appreciated
  3 个评论

请先登录,再进行评论。

采纳的回答

Walter Roberson
Walter Roberson 2016-3-27
Do not use "path" as a variable name, as that interferes with the MATLAB path.
Calling the generated path "gpath", then:
IDX = 1;
while IDX <= length(gpath)
dpos = find(gpath==gpath(IDX),1,'last');
if dpos > IDX
gpath(IDX+1:dpos) = [];
end
IDX = IDX + 1;
end
This is guaranteed to take no more than length(gpath) steps.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Genetic Algorithm 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by