How to construct an undirected graph by reading edge by edge from a text file
1 次查看(过去 30 天)
显示 更早的评论
Suppose I have a list of edges in a text file(dont know how many edges are there in a text file). I have to create an undirected graph from it. Finally I have to construct first order transition probability matrix from that graph. for example for the edges={a,b}, {a,c}, {a,d}, the transition matrix is [0 1/3 1/3 1/3;1 0 0 0; 1 0 0 0;1 0 0 0]
3 个评论
回答(2 个)
Josh Meyer
2017-9-6
You can use textscan to read the text file into a cell array, with the first entry listing the source nodes and the second entry listing the target nodes. Then you can create the graph directly from the cell array columns.
fid = fopen('textfile.txt');
C = textscan(fid,'%s%s')
fclose(fid);
G = graph(C{1},C{2})
If the file lists duplicate edges (for an undirected graph a->b and b->a is a duplicate edge, so the example file you provided contains duplicates) you'll need to trim those away first. One method is to convert to a char array, sort the edges, find the unique rows, then convert back to a cell array:
C = cell2mat([C{1} C{2}]);
C = unique(sort(C,2),'rows');
C = num2cell(C)
G = graph(C(:,1),C(:,2))
2 个评论
Christine Tobler
2017-9-6
I agree with the way you're constructing the graph here, Josh. To get the transition matrix from a graph, use the following code:
T = adjacency(g) ./ degree(g);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Undirected Graphs 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!