How to remove duplicate nodes from generated path and segments inbetween?
8 次查看(过去 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!