Google
 

2/16/07

Using C++ to read a tab seperated Matlab matrix

#include <iostream>
#include <istream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include <iterator>
#include <algorithm> // for copy

using namespace std;

// template <class T>
// std::vector<T> StringToVec( const std::string& Str );
// Tokenize a passed line/string into a vector
// e.g:
// std::string str = "1 2 3 4";
// std::vector<int> vec = StringToVector<int>(str);

template <class T>
vector<T> StringToVec( const string &str )
{
vector<T> MyVec;
istringstream iss (str, istringstream::in);
copy(istream_iterator<T>(iss), istream_iterator<T>(), back_inserter(MyVec)); //check http://www.sgi.com/tech/stl/istream_iterator.html
return MyVec;
}

The following use the above template to read in a big matrix from a file. Using C++ to read big matrix from a file, need the above code.


int main()
{
vector< vector<float> > Matrix;
vector<float> Row;
string Line;
ifstream in("./test.dat");
if( !in ) {
cerr << "can't open file" << endl;
return false;
}

// read matrix row's
while( getline( in, Line) ) {
Row = StringToVec<float>( Line );
Matrix.push_back( Row );
Row.clear();
}

// output the matrix
for( vector< vector<float> >::iterator IterRow = Matrix.begin(); IterRow !=
Matrix.end(); ++IterRow ) {
for( vector<float>::iterator IterCol = IterRow->begin(); IterCol !=
IterRow->end(); ++IterCol ) {
cout << *IterCol << " ";
}
cout << endl;
}

return 1;

}

No comments: