Search code examples
matlabrandomsparse-matrixadjacency-matrix

Generating random weighted adjacency matrix in MATLAB


I would like to create a random adjacency matrix in MATLAB such that the total sum of weight is equal to the number of edges. Finally find the Laplacian matrix using

L = diag(sum(A)) - A

and then graph it. Is there any way to do so? Thanks in advance.


Solution

  • An adjacency matrix for an undirected graph is simply a square symmetric matrix.
    If you have no constraints on the degree of the nodes only on the weights than I would suggest something like

    n ; % number of nodes in the graph
    density = 1e-3; % a rough estimate of the amount of edges       
    A = sprand( n, n, density ); % generate adjacency matrix at random
    % normalize weights to sum to num of edges
    A = tril( A, -1 );    
    A = spfun( @(x) x./nnz(A), A );    
    % make it symmetric (for undirected graph)
    A = A + A.';
    

    I have used in this code:

    • sprand to generate random sparse matrix.
    • spfun to help normalize the edge weights.
    • tril to extract only half the matrix.