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'})`