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
2016-3-27
Over in http://www.mathworks.com/matlabcentral/answers/275204-how-to-remove-duplicate-nodes-from-generated-path-and-segments-inbetween, Guillaume is waiting for you to give an example of where it would run forever.
采纳的回答
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 Center 和 File Exchange 中查找有关 Genetic Algorithm 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!