Reputation: 63
How can I load data of a sparse matrix form (MMF) file, and then carry out a linear algebra operation on that matrix?
The MMF file is in the following form:
1 1 8.530175905456780E+008
7 1 1.257919566068602E+008
12 1 3.841933299769016E+002
13 1 1.257919566068601E+008
18 1 -3.841933299769017E+002
67 1 -1.214247928031784E+008
68 1 3.613935214862212E+007
72 1 9.604833249423183E+001
73 1 -3.094511662733424E+008
79 1 -1.214247928031783E+008
80 1 -3.613935214862211E+007
84 1 -9.604833249423186E+001
2 2 8.530175905456780E+008
8 2 -3.094511662733424E+008
14 2 -3.094511662733426E+008
67 2 3.613935214862212E+007
68 2 -1.214247928031784E+008
72 2 9.604833249423183E+001
74 2 1.257919566068602E+008
78 2 3.841933299769016E+002
79 2 -3.613935214862212E+007
80 2 -1.214247928031783E+008
84 2 9.604833249423183E+001
........
It is of size up to 6500.
Upvotes: 0
Views: 411
Reputation: 63
Well, I figured it out by using the following code (where n is the matrix size):
import numpy as np
from numpy import *
from matplotlib.pyplot import *
import re
import scipy.linalg as la
data = loadtxt('matKSMMF.txt', skiprows=8)
s = len (data)
print(s)
n = 6567
kmat = [[0 for _ in range(n)] for _ in range(n)]
for x in range (s):
m = data[x:x+1, :]
kmat[int (m[0, 0]) - 1][int (m[0, 1]) - 1] = m[0, 2]
K = np.array(kmat)
print (K)
Upvotes: 0
Reputation: 6327
From the documentation of mmread in SciPy:
scipy.io.mmread(source)[source]
Reads the contents of a Matrix Market file-like ‘source’ into a matrix.
Parameters sourcestr or file-like Matrix Market filename (extensions .mtx, .mtz.gz) or open file-like object.
Returns andarray or coo_matrix Dense or sparse matrix depending on the matrix format in the Matrix Market file.
SciPy should return a sparse matrix, if that is the format of the file.
Try:
import scipy
sparse_mat = scipy.io.mmread('matrix_file_name.mtx')
Upvotes: 2