Ask Your Question

Revision history [back]

The Matrix Market is

a visual repository of test data for use in comparative studies of algorithms for numerical linear algebra, featuring nearly 500 sparse matrices from a variety of applications, as well as matrix generation tools and services

proposed by the National Institute of Standards and Technology (NIST), a branch of the US Department of Commerce. As the Matrix Market info page puts it,

The Matrix Market is a component of the NIST project on Tools for Evaluation of Mathematical and Statistical Software which has focus areas in linear algebra, special functions and statistics.

The .mtx Matrix Market Exchange format is documented on the NIST page on Matrix Market Exchange formats.

Having saved the following into a file called adjacency.mtx:

%%MatrixMarket matrix coordinate real symmetric
%
% adjacency matrix for a graph
%
5 5 6
1 2 1.000e+00
1 3 1.000e+00
1 5 1.000e+00
2 4 1.000e+00
3 4 1.000e+00
4 5 1.000e+00

one can use input-output functionality in SciPy to read that file into a SciPy sparse matrix:

sage: from scipy.io import mmread
sage: a = mmread('adjacency.mtx')

which is represented as follows:

sage: a
<5x5 sparse matrix of type '<type 'numpy.float64'>'
    with 12 stored elements in COOrdinate format>

and, if one want the list of its entries, prints out as follows:

sage: print(a)
  (0, 1)    1.0
  (0, 2)    1.0
  (0, 4)    1.0
  (1, 3)    1.0
  (2, 3)    1.0
  (3, 4)    1.0
  (1, 0)    1.0
  (2, 0)    1.0
  (4, 0)    1.0
  (3, 1)    1.0
  (3, 2)    1.0
  (4, 3)    1.0

One can convert it to a SciPy dense matrix:

sage: b = a.todense()
sage: b
matrix([[ 0.,  1.,  1.,  0.,  1.],
        [ 1.,  0.,  0.,  1.,  0.],
        [ 1.,  0.,  0.,  1.,  0.],
        [ 0.,  1.,  1.,  0.,  1.],
        [ 1.,  0.,  0.,  1.,  0.]])

and then convert that to a Sage matrix:

sage: c = matrix(b)
sage: c
[0.0 1.0 1.0 0.0 1.0]
[1.0 0.0 0.0 1.0 0.0]
[1.0 0.0 0.0 1.0 0.0]
[0.0 1.0 1.0 0.0 1.0]
[1.0 0.0 0.0 1.0 0.0]

from which one can create a graph:

sage: g = Graph(c)
sage: g
Graph on 5 vertices
sage: g.plot()
Launched png viewer for Graphics object consisting of 12 graphics primitives

Alternatively, to call Octave or MATLAB from SageMath, one can use the corresponding interfaces:

but for the needs of this question, that should not be necessary.

In summary:

sage: from scipy.io import mmread
sage: g = Graph(matrix(mmread('adjacency.mtx').todense()))