push_back MatDoub


totally_noob
04-22-2008, 04:32 AM
Hi there,

I want to add elements to MatDoub, can this be done dynamically through push back?

Also, I am reading in my data file through the use of vector < vector <string> >, but want to swap the data in vector < vector <string> > to MatDoub....how do i do this? I'm feeling out of my depth!

Cheers

void openfile::read(char* fname)
{
ifstream in(fname);

string element, delimiters = ",\n\r";


int row = 0;
char ch;

data.push_back( vector <string>() );

while( in.read( (char*)&ch, 1 ) )
{

if( delimiters.find_first_of(ch) == delimiters.npos )
{
element += ch;
}
else
{
if( ch != '\r' )
{
data[row].push_back( element );
element = "";

if( ch == '\n' )
{
data.push_back( vector <string>() );
row++;
}
}
}
}

if( element.size() > 0 )
data[row].push_back( element );

in.close();
cols = data[0].size();
rows = data.size();
// MatDoub matrix(rows,cols);
// matrix = data;
}{

davekw7x
04-22-2008, 11:05 AM
Hi there,

I want to add elements to MatDoub, can this be done dynamically through push back? If you are absolutely certain that your routine pushes the vectors of strings corresponding to the rows absolutely correctly, and the individual strings on in the row vector contain the separate matrix values, then, assuming that the MatDoub has been declared (is it an element of the class?), you have to convert each element of each string vector to a double.

You can resize the MatDoub, based on the number of rows and columns that you have read from the file.

Then you can use stringstream to convert individual strings to doubles on each row and set matrix elements to the result of each conversion.

I added a print statement so that you can see the elements as they are converted...


cols = data[0].size();
rows = data.size();
// assume the MatDoub matrix is member of the class
// and was declared in its constructor
matrix.resize(rows,cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
stringstream ss(data[i][j]);
ss >> matrix[i][j];
if (!ss) {
cerr << "There was a problem converting element ["
<< i << "][" << j << "]" << endl;
throw("Exiting program"); // or simply exit(EXIT_FAILURE)
}
cout << "matrix[" << i << "][" << j << "] = "
<< setw(13) << setprecision(6) << scientific << matrix[i][j]
<< endl;
}
}



Regards,

Dave