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

2 visualizaciones (últimos 30 días)
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 comentarios
Xi Wen Lim
Xi Wen Lim el 29 de Mzo. de 2016
@Walter,
Thank you for the notice. I did not realise Guailaume had responded

Iniciar sesión para comentar.

Respuesta aceptada

Walter Roberson
Walter Roberson el 27 de Mzo. de 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 comentario
Xi Wen Lim
Xi Wen Lim el 29 de Mzo. de 2016
Thank you very much Walter! I have no problems with running this code even with many elements.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Genetic Algorithm en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by