Load A Matrix from An ASCII Format File (C++ and Python)

It is common for an scientific program to load an ASCII format matrix file, i.e. an ASCII text file consisting of lines of float numbers separated by whitespaces. In this post, I am gonna show my code (C++ and Python) to load a matrix from an ASCII file.

C++

The following C++ function is to load a matrix from an ASCII file into a vector< vector > object, some kind of “C++ style” 2D array.

The code is also available on GitHub Gist.

Python

The Python code loads the matrix into a numpy.matrix object.

The code is also available on GitHub Gist.

If you want to get a nested list instead of such a numpy.matrix object, you can use the following lines to convert the object to a nested list: