Search code examples
matlabadjacency-matrix

Convert adjacency matrix to specific edge list in MATLAB


If I have the matrix

  1 0 0  
  0 0 1 
  0 0 0 

and I want this form in MATLAB

1 2 3  1 2 3  1 2 3
1 1 1  2 2 2  3 3 3
1 0 0  0 0 0  0 1 0

also I want the values of third row in result. i.e. ans= [1 0 0 0 0 0 0 1 0]


Solution

  • Here you go -

    [X,Y] = ndgrid(1:size(A,1),1:size(A,2));
    out = [X(:).' ; Y(:).' ; A(:).']
    

    For the last part of your question, use the last row of out : out(end,:) or A(:).'.

    Sample run -

    >> A
    A =
         1     0     0
         0     0     1
         0     0     0
    >> [X,Y] = ndgrid(1:size(A,1),1:size(A,2));
    >> out = [X(:).' ; Y(:).' ; A(:).']
    out =
         1     2     3     1     2     3     1     2     3
         1     1     1     2     2     2     3     3     3
         1     0     0     0     0     0     0     1     0