Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way of converting large adjacency matrices to edge lists in MATLAB?

I have large sparse adjacency matrices with around 1M nodes, which I am processing with MATLAB. I want to convert these matrices into network edge lists as efficiently as possible. As an example adjacency matrix to illustrate this:

adj =
     1     0     1     0
     0     0     1     1
     0     0     1     0
     0     1     0     0

And the output I call an network edge list here is:

>> adj2edgeList_Alex(adj)
ans =
     0     0
     0     2
     1     2
     1     3
     2     2
     3     1

This code which I have to do it stalls for time.

function edge_list = adj2edgeList_Alex(graph)

edge_num = length(logical(graph > 0));
edge_list = zeros(edge_num,2);
row_ind = 1;
for ii=1:size(graph,2)
    ind_temp = find(graph(ii,:)==1);
    if(isempty(ind_temp) == 0)
        ind_temp = ind_temp - 1;
        edges_iter = length(ind_temp);   
        node_num = ii - 1;
        edge_list(row_ind:row_ind+edges_iter-1,:) = ...
            [(node_num)*ones(1,edges_iter);ind_temp]';
            row_ind = row_ind + edges_iter;
    end
end

Is there a modification to speed this up? Another function or toolbox that can perform better?

like image 716
Vass Avatar asked Apr 24 '13 16:04

Vass


1 Answers

You can use find():

[r,c] = find(adj)
edges = [r,c];

Note that MATLAB indexes from 1 not 0, but you can rebase by simply edges-1.

like image 125
Oleg Avatar answered Sep 23 '22 15:09

Oleg