How to remove duplicate nodes from generated path and segments inbetween?
조회 수: 9 (최근 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.
댓글 수: 0
채택된 답변
Guillaume
2016년 3월 24일
편집: Guillaume
2016년 3월 29일
Seems like you want to delete everything between the first and last occurrence of any identical digit:
path = [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];
while true
pathvalues = unique(path);
pathhist = histcounts(path, [pathvalues, Inf]);
duplicate = pathvalues(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
댓글 수: 5
Guillaume
2016년 3월 29일
편집: Guillaume
2016년 3월 29일
Oh, there was a big bug in the code where I found which value was duplicated. I've edited my answer to fix the bug.
The lines
pathhist = histcounts(path, [unique(path), Inf]);
duplicate = path(find(pathhist > 1, 1)); %find identical digit
have been changed to
pathvalues = unique(path);
pathhist = histcounts(path, [pathvalues, Inf]);
duplicate = pathvalues(find(pathhist > 1, 1)); %find identical digit
추가 답변 (1개)
Teja Muppirala
2016년 3월 29일
편집: Teja Muppirala
2016년 3월 29일
path = [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];
N = numel(path);
G = sparse(path(1:end-1),path(2:end),1,N,N); %Make adjacency matrix
G = digraph(G);
pathOut = shortestpath(G, path(1), path(end),'Method','unweighted')
The answer is:
pathOut =
1 6 7 12 11 16 21 22 23 24 19 20 25
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Function Creation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!