List of Node pairs

3 ビュー (過去 30 日間)
Hari
Hari 2021 年 7 月 15 日
回答済み: Akira Agata 2021 年 7 月 16 日
How can I get a matrix of node pairs from a graph? That is, if there are 4 nodes 1,2,3,4, then the node pair matrix would be :
1 2
1 3
1 4
2 1
2 3
2 4
3 2 etc.
I could do this using 2 for loops, but is there any quick way of doing it?
  2 件のコメント
Akira Agata
Akira Agata 2021 年 7 月 16 日
Questions for clarification:
  • You want to obtain node pair matrix from graph object ?
  • If the graph has an edge from node m to node n, you need both (n, m) and (n, m) in your matrix?
Hari
Hari 2021 年 7 月 16 日
Sorry if the question was confusing. I need to get the list of node pairs but it need not be from the graph object. Knowing the number of nodes in the graph would be sufficient I guess. If there are 4 nodes in the graph then the output should be:
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
etc..
The edges in the graph is not important here.

サインインしてコメントする。

採用された回答

Akira Agata
Akira Agata 2021 年 7 月 16 日
Another possible solution:
numNode = 4;
[r,c] = find(~eye(numNode));
v = [c,r];
>> v
v =
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3

その他の回答 (2 件)

Simon Chan
Simon Chan 2021 年 7 月 16 日
Basically you just want to create the matrix, right?
u=1:4;
u_entend = repelem(u,1,length(u)-1);
w = repmat(u',1,length(u));
v = reshape(tril(w,-1) + triu(w,1),1,[]);
v = v(v~=0);
node_pair = [u_entend;v]'
Result:
node_pair =
1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3

Walter Roberson
Walter Roberson 2021 年 7 月 16 日
u=1:4;
[s,t] = ndgrid(u);
v = [s(:),t(:)];
mask = v(:,1) ~= v(:,2);
v = v(mask,:);
v
v = 12×2
2 1 3 1 4 1 1 2 3 2 4 2 1 3 2 3 4 3 1 4

カテゴリ

Help Center および File ExchangeGraph and Network Algorithms についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by