在MATLAB中创建邻接矩阵图

时间:2017-05-06 17:59:49

标签: matlab graph adjacency-matrix

我有以下邻接矩阵:

this is my adjacency matrix

行代表B1B8 该列将W1显示为W8

如何创建它的图形表示?

1 个答案:

答案 0 :(得分:2)

您可以使用内置digraph(在R2015b中引入)函数来表示邻接矩阵:

A = round(rand(8)); % create adjacency matrix
plot(digraph(A)); % plot directed graph

Directed graph

如果是对称矩阵,您可以使用graph(在R2015b中引入)绘制无向图:

A = rand(8);
A = round((A+A.')/2); % create a symmetric adjacency matrix
plot(graph(A)); % plot undirected graph

Undirected graph

将邻接矩阵转换为预期格式

MATLAB期望行ans列在邻接矩阵中具有相同的含义,但问题并非如此。因此,我们应该添加虚拟行(W1W8)和列(B1B8)。

A_ = round(rand(8)); % creates your adjacency matrix
A = [zeros(size(A_))' A_; A_' zeros(size(A_))]; % converts to the expected format

% gives the columns a points a name 
names = {'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8'};
plot(graph(A, names)); % create the undirected graph as demonstrated earlier

enter image description here

<强>替代

  • Using gplot可能对较旧的MATLAB版本有用

    gplot(A, [zeros(8, 1) (1:8)'; 5*ones(8, 1) (1:8)'])
    set(gca,'XTick',[0 5])
    set(gca,'XTickLabel',{'B', 'W'})
    

从R0126b开始,最后两行可以写得更好:

xticks([0 5]);
xticklabels({'B', 'W'})`

enter image description here