Created
March 18, 2014 04:18
-
-
Save kevinavery/9613505 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
def loadSparseMatrix(filename): | |
""" | |
Loads the sparse matrix in text file `filename` assuming the | |
Matlab format. | |
Each row of the file should specify the non-zero value | |
at a particular location, using 1 based indexes, formatted as follows: | |
axis1_index (...) axisN_index value | |
The Matlab equivalent `load` then `spconvert`. See here for details: | |
http://www.mathworks.com/help/matlab/ref/spconvert.html | |
Note that it infers the shape of the matrix from the maximum | |
indicies in the file. This is a limitation of file format. | |
""" | |
DATA = np.loadtxt(filename) | |
dims = DATA.shape[1] - 1 | |
shape = [np.max(DATA[:,i]) for i in range(dims)] | |
M = np.zeros(shape=shape) | |
for row in DATA: | |
index = tuple(row[:-1] - 1) | |
M.itemset(index, row[-1]) | |
return M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment