简体   繁体   中英

Create graph of adjacency matrix in MATLAB

I have the following adjacency matrix:

这是我的邻接矩阵

The rows represents B1 to B8 and the column presents W1 to W8 .

How can I create a graphical representation of it?

You can use the builtin digraph (introduced in R2015b) function to represent an adjacency matrix:

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

有向图

In case of a symmetric matrix, you can plot an undirected graph using graph (introduced in R2015b too):

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

无向图

Converting your adjacency matrix to the expected format

MATLAB expects that the rows ans columns have the same meaning in an adjacency matrix, which is not the case in your question. Therefore, we should add dummy rows (for W1 to W8 ) and columns (for B1 to B8 ).

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

在此处输入图片说明

Alternatives

  • Using gplot may be useful for older MATLAB versions

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

From R0126b, the last two lines may be written somewhat nicer as:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM