Search code examples
matlabgraphplotgraph-theorygraph-visualization

How to draw networks in Matlab?


I have a matrix A in Matlab of dimension mx2 that contains in each row the labels of two nodes showing a direct link in a network, e.g.:

if the network has 4 nodes the matrix A could be A=[1 2; 1 3; 2 1; 2 4; 3 2; 4 1; 4 2], where the first row means that there is a link from 1 to 2, the second row means that there is a link from 1 to 3, etc.

Could you suggest me a quick way to draw the network from A?


Solution

  • If you want the links to be directional, and have the Bioinformatics toolbox, you can create a biograph object. This also allows for labelling the nodes with identification strings if you so desire, see the help file. If not they'll be called "Node 1", "Node 2", etc. You'll need to convert your list of links to an adjacency matrix - @RTL gave the accumarray version, you can also use sub2ind:

    N = 4;
    adj = zeros(N);
    adj(sub2ind([N,N], A(:,1),A(:,2))) = 1;
    
    bg = biograph(adj);  % make biograph object
    dolayout(bg);   % automatically calculate positions for nodes
    view(bg); % what it says on the tin