Last active
December 10, 2015 12:58
-
-
Save xuhdev/4437648 to your computer and use it in GitHub Desktop.
load matrix from an ascii file into a numpy.matrix object.
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
def load_matrix_from_file(f): | |
""" | |
This function is to load an ascii format matrix (float numbers separated by | |
whitespace characters and newlines) into a numpy matrix object. | |
f is a file object or a file path. | |
""" | |
import types | |
import numpy | |
if type(f) == types.StringType: | |
fo = open(f, 'r') | |
matrix = load_matrix_from_file(fo) | |
fo.close() | |
return matrix | |
elif type(f) == types.FileType: | |
file_content = f.read().strip() | |
file_content = file_content.replace('\r\n', ';') | |
file_content = file_content.replace('\n', ';') | |
file_content = file_content.replace('\r', ';') | |
return numpy.matrix(file_content) | |
raise TypeError('f must be a file object or a file name.') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment