Ordering rows based on value
古いコメントを表示
Suppose I have a matrix of values as follows:
matches = [1,2;1,4;2,5;3,4;3,6;5,6;];
Is there a way to "connect these rows together based on a common value in the rows column. The desired result is as follows:
connected = [1,2,5,6,3,4,1]
採用された回答
その他の回答 (2 件)
Geoff
2012 年 4 月 13 日
Try this:
matches = [1,2;1,4;2,5;3,4;3,6;5,6;];
connected = matches(1);
while size(matches,1) > 0
[r,c] = find(matches == connected(end), 1);
if isempty(r)
disp('End of chain');
break;
end
connected(end+1) = matches(r, 3-c);
matches(r,:) = [];
end
disp(connected);
It's a little destructive. It systematically removes rows from the matches matrix until there are no more links or there are no rows left. It copes with ambiguity (if there is any) by selecting the first available value (determined by whatever find deems as the first value). In some some cases, this might end the chain prematurely.
3 件のコメント
Harold
2012 年 4 月 13 日
Geoff
2012 年 4 月 13 日
Well it depends on your data. For this data, it's fine. And maybe you'll always throw 'sane' data at it. I just imagined that some data sets won't produce a closed loop, will branch, or contain a side-loop that itself is closed.
Imagine the above data with [6 7; 7 8; 8 3] on it. If we happen to follow [6 7] instead of [3 6] then we'll touch all the values: [1 2 5 6 7 8 3 4 1]. But if we follow [3 6] first, we'll skip over the side-loop and produce the original output.
Anyway, I just think about that stuff, but I don't know what your data is representing or what its constraints are. If this solves your problem I'm happy. Don't forget to close off the question by accepting.
Harold
2012 年 4 月 13 日
Harold
2012 年 4 月 13 日
3 件のコメント
Geoff
2012 年 4 月 13 日
Well, that's okay, but I meant that I don't know WHY your data is like it is. What do the lines represent? Why do they have anything in common with other rows? Is this a polygon?
If you worry about things that can't happen when writing an algorithm then you waste time coding. Conversely, if you don't consider all possibilities then you waste time debugging.
If the system forms a closed loop, then my answer should work. But whether it comes out clockwise or anticlockwise will depend on what order the data is presented.
Harold
2012 年 4 月 13 日
Harold
2012 年 4 月 13 日
カテゴリ
ヘルプ センター および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!