Python 如何编写脚本,使用函数scipy.io.mmread从mtx文件读取矩阵?

Python 如何编写脚本,使用函数scipy.io.mmread从mtx文件读取矩阵?,python,matrix,sparse-matrix,Python,Matrix,Sparse Matrix,我收到了一个文件(称为matrix.mtx),打开该文件时如下所示: %%MatrixMarket matrix coordinate real symmetric 132 132 1890 1 1 1.9960268182200e+03 2 1 5.6751562001600e+02 3 1 7.7541907594400e+02 6 1 -8.0165406828800e+02 7 1 -1.3864718750000e+03 13 1 -1.2338727

我收到了一个文件(称为matrix.mtx),打开该文件时如下所示:

%%MatrixMarket matrix coordinate real symmetric  
132 132 1890  
1 1  1.9960268182200e+03  
2 1  5.6751562001600e+02  
3 1  7.7541907594400e+02  
6 1 -8.0165406828800e+02  
7 1 -1.3864718750000e+03  
13 1 -1.2338727484800e+00  
18 1 -5.9225891927100e+02  
19 1 -4.9040995231500e+02  
20 1 -4.8997371242200e+02  
。。。等等


我需要编写一个脚本,使用函数scipy.io.mmread从文件matrix.mtx读取矩阵。此函数将以稀疏格式存储矩阵。它说矩阵是以矩阵市场格式存储的。我很难让它工作,任何帮助都将不胜感激。

使用以下更简单的矩阵,也存储在
matrix.mtx中

%%MatrixMarket matrix coordinate real symmetric
3 3 6
1 1  1.9960268182200e+03
2 1  5.6751562001600e+02
3 1  7.7541907594400e+02
2 2 -8.0165406828800e+02
3 2 -1.3864718750000e+03
3 3 -5.9225891927100e+02
下面将文件读入稀疏矩阵

In [1]: from scipy.io import mmread

In [2]: a = mmread('matrix.mtx')

In [3]: a
Out[3]:
<3x3 sparse matrix of type '<type 'numpy.float64'>'
    with 9 stored elements in COOrdinate format>
还是数组

In [5]: a.toarray()
Out[5]:
array([[ 1996.02681822,   567.51562002,   775.41907594],
       [  567.51562002,  -801.65406829, -1386.471875  ],
       [  775.41907594, -1386.471875  ,  -592.25891927]])
In [5]: a.toarray()
Out[5]:
array([[ 1996.02681822,   567.51562002,   775.41907594],
       [  567.51562002,  -801.65406829, -1386.471875  ],
       [  775.41907594, -1386.471875  ,  -592.25891927]])