Re: tab-delimited file to graph
- To: mathgroup at smc.vnet.net
- Subject: [mg69469] Re: tab-delimited file to graph
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Wed, 13 Sep 2006 04:02:54 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <ee64q5$7s4$1@smc.vnet.net>
aitor69gonzalez at gmail.com wrote:
> Hello,
>
> I have a directed graph "mygraph" in a tab delimited file that looks
> like this:
> v1 v2
> v2 v3
> v3 v1
> v1 v4
> I would like to import this graph into mathematica, so that I can take
> advantage of the -DiscreteMath`Combinatorica`- functions. So far, I was
> only able to import it with Import["mygraph","TSV"] into a list of
> two-item lists. Now, I am stuck there. Can somebody help me to convert
> this list of two-item lists into a matrix or adjacency list of a
> directed graph?
>
> Thank you in advance,
>
> Aitor
>
Hi Aitor,
Building an adjacency matrix from a list of pairs can be achieve with
the function SparseArray. In the following, I will assume that the
element of your list are literally named v1, v2, ..., vn. First we
transform the pairs {vi,vj} into the pairs of numerical indices {i, j}.
Then we build the replacement rules expected by SparseArray thanks to
the function Thread. Finally, we build the matrix as a sparse array that
contains 1 wherever two vertices are adjacent and 0 everywhere else.
Note that a sparse array is a compact structure, highly efficient in
terms of memory usage. You may want to see the sparse array as a regular
dense matrix, however. You can do that by using the Normal function.
lst = {{v1, v2}, {v2, v3}, {v3, v1}, {v1, v4}};
{v1, v2, v3, v4} = Range[4]
--> {1, 2, 3, 4}
lst
--> {{1, 2}, {2, 3}, {3, 1}, {1, 4}}
rls = Thread[lst -> Table[1, {Length[lst]}]]
--> {{1, 2} -> 1, {2, 3} -> 1, {3, 1} -> 1, {1, 4} -> 1}
SparseArray[rls];
MatrixForm[Normal[SparseArray[rls]]]
-->
0 1 0 1
0 0 1 0
1 0 0 0
Best regards,
Jean-Marc