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

2 Ansichten (letzte 30 Tage)
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 Kommentare
Xi Wen Lim
Xi Wen Lim am 29 Mär. 2016
@Walter,
Thank you for the notice. I did not realise Guailaume had responded

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 27 Mär. 2016
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.
  1 Kommentar
Xi Wen Lim
Xi Wen Lim am 29 Mär. 2016
Thank you very much Walter! I have no problems with running this code even with many elements.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by