I have the following matrix A[10,6]
ans =
1 1 0 0 0 1
1 1 1 1 0 0
1 1 1 1 0 0
1 0 0 0 1 1
1 1 0 0 0 0
0 1 1 1 0 1
1 0 0 1 0 1
0 1 1 1 1 1
0 1 1 1 1 1
1 1 1 0 1 1
I want to create a directed graph from that matrix, My graph will contain one node for each column and one node for every two lines (so a total of 11 nodes). if possible distinguish between them.
For the edges , I have two cases :
- An edge from a column node to a line node is added for all the 1 in the first line of the node in the matrix.
- An edge from the line node to a column node is added for all the 1 in the second line of the node in the matrix.
I made some research in the graph section of the documentation but couldn't get it done .
Thanks

 採用された回答

alice
alice 2017 年 6 月 21 日

1 投票

To get a directed graph, you should use digraph function. In order to do so, you have to build a standard square adjacency matrix describing how your nodes are connected. This is one way to do it (choosing to put the column nodes first in the adjacency matrix):
nNodeCol = size(A,2); % one node for each column of A
nNodeLine = size(A,1)/2; % one node for every two lines of A
% First the column nodes, then the line nodes:
nodeNames = [cellstr(strcat('column', num2str((1:size(A,2))'))) ; cellstr(strcat('line', num2str((1:size(A,1)/2)')))];
% Adjacency matrix adj, adj(i,j)=1 means there is an edge from node#i to node#j:
adj = zeros(nNodeCol+nNodeLine); % square matrix which size is the number of nodes
adj(1:nNodeCol, nNodeCol+1:end) = A(1:2:end,:)'; % edge from a column node to a line node is added for all the 1 in the first line of the node in the matrix
adj(nNodeCol+1:end, 1:nNodeCol) = A(2:2:end,:); % edge from the line node to a column node is added for all the 1 in the second line of the node in the matrix
% Here is your graph:
G = digraph(adj,nodeNames);
plot(G);

3 件のコメント

stam dadi
stam dadi 2017 年 6 月 21 日
編集済み: stam dadi 2017 年 6 月 21 日
Thanks for your answer. the problem is fixed
stam dadi
stam dadi 2017 年 6 月 22 日
I want to do a depth search using the function
dfsearch
But I need the name of nodes, how to get them from the previous graph declaration ...Thank's
alice
alice 2017 年 6 月 23 日
The names are in the cell nodeNames.
To get the node names from a graph G, you can simply use G.Nodes .

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeGraph and Network Algorithms についてさらに検索

質問済み:

2017 年 6 月 20 日

コメント済み:

2017 年 6 月 23 日

Community Treasure Hunt

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

Start Hunting!

Translated by