Changeset 17


Ignore:
Timestamp:
Jul 8, 2003, 5:26:35 PM (19 years ago)
Author:
Peter
Message:

Added a constructor that initializes a matrix with data from an istream.

Location:
trunk/src
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/matrix.cc

    r12 r17  
    11
    22#include <iostream>
     3#include <string>
     4#include <sstream>
     5#include <vector>
     6
    37#include "matrix.h"
    48
     
    4145}
    4246
     47
     48// Constructor that gets data from istream
     49matrix::matrix(std::istream& is)
     50{
     51  using namespace std;
     52
     53  // read the data file and store in stl vectors (dynamically expandable)
     54  std::vector<std::vector<double> > data_matrix;
     55  u_int nof_columns=0;
     56  u_int nof_rows = 0;
     57  string s;
     58  for (nof_rows = 0; getline(is, s, '\n'); nof_rows++) {
     59   istringstream line(s);
     60   std::vector<double> v;
     61   double t;
     62   while (line >> t) {
     63    if(!is.good()) {
     64     cerr << "matrix::matrix(std::istream&): "
     65    << "non-double value in data file!" << endl;
     66     exit(1);
     67    }
     68    v.push_back(t);
     69   }
     70   if(nof_columns==0)
     71     nof_columns=v.size();
     72   else if(v.size()!=nof_columns) {
     73    cerr << "matrix::matrix(std::istream&) data file error: "
     74   << "line" << nof_rows+1 << " has " << v.size()
     75   << " columns; expected " << nof_columns
     76   << " columns"
     77   << endl;
     78    exit(1);
     79   }
     80   data_matrix.push_back(v);
     81  }
     82
     83  // convert the data to a gsl matrix
     84  m_ = gsl_matrix_alloc ( nof_rows, nof_columns );
     85  for(u_int i=0;i<nof_rows;i++)
     86    for(u_int j=0;j<nof_columns;j++)
     87      gsl_matrix_set( m_, i, j, data_matrix[i][j] );
     88}
    4389
    4490matrix::~matrix()
     
    131177{
    132178  using namespace std;
    133   s_out.setf( ios::fixed ); 
     179  s_out.setf( ios::dec );
     180  s_out.precision(12);
    134181  for( size_t i = 0, j = 0; i < a.rows(); ++i )
    135182    {
  • trunk/src/matrix.h

    r12 r17  
    4646
    4747
     48
     49 
    4850    /**
    4951  Copy constructor
     
    5961    matrix( gsl_matrix* );
    6062   
     63
     64    /**
     65       Constructor taking as only argument a an istream that should
     66       contain the matrix where columns are separated with whitespace
     67       (not '\n') and rows by '\n'.
     68    */
     69    matrix(std::istream &);
     70
    6171    /**
    6272       Destructor will clear matrix's allocated memory
Note: See TracChangeset for help on using the changeset viewer.