2019-01-08 17:12:05 +01:00
|
|
|
/* $Header: /var/lib/cvs/dynare_cpp/sylv/testing/MMMatrix.cpp,v 1.1.1.1 2004/06/04 13:01:13 kamenik Exp $ */
|
|
|
|
|
|
|
|
/* Tag $Name: $ */
|
|
|
|
|
|
|
|
#include "MMMatrix.hh"
|
|
|
|
|
2019-01-25 15:27:20 +01:00
|
|
|
#include <fstream>
|
|
|
|
#include <iomanip>
|
2019-01-08 17:12:05 +01:00
|
|
|
|
2019-01-25 15:27:20 +01:00
|
|
|
MMMatrixIn::MMMatrixIn(const std::string &fname)
|
2019-01-08 17:12:05 +01:00
|
|
|
{
|
2019-01-25 15:27:20 +01:00
|
|
|
std::ifstream fd{fname};
|
|
|
|
if (fd.fail())
|
|
|
|
throw MMException("Cannot open file "+fname+" for reading\n");
|
2019-01-08 17:12:05 +01:00
|
|
|
|
|
|
|
// jump over initial comments
|
2019-01-25 15:27:20 +01:00
|
|
|
while (fd.peek() == '%')
|
|
|
|
fd.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
|
|
|
|
|
2019-01-08 17:12:05 +01:00
|
|
|
// read in number of rows and cols
|
2019-01-25 15:27:20 +01:00
|
|
|
fd >> rows >> cols;
|
|
|
|
if (fd.fail())
|
2019-01-08 17:12:05 +01:00
|
|
|
throw MMException("Couldn't parse rows and cols\n");
|
|
|
|
// read in data
|
|
|
|
int len = rows*cols;
|
2019-02-14 11:29:18 +01:00
|
|
|
data.resize(len);
|
2019-01-08 17:12:05 +01:00
|
|
|
int i = 0;
|
2019-01-25 15:27:20 +01:00
|
|
|
while (!fd.eof() && i < len)
|
2019-01-08 17:12:05 +01:00
|
|
|
{
|
2019-02-14 11:29:18 +01:00
|
|
|
fd >> data[i];
|
2019-01-25 15:27:20 +01:00
|
|
|
if (fd.fail())
|
|
|
|
throw MMException("Couldn't parse float number\n");
|
2019-01-08 17:12:05 +01:00
|
|
|
i++;
|
|
|
|
}
|
|
|
|
if (i < len)
|
2019-01-25 15:27:20 +01:00
|
|
|
throw MMException("Couldn't read all " + std::to_string(len) + " elements, read "
|
|
|
|
+ std::to_string(i) + " so far\n");
|
|
|
|
fd.close();
|
2019-01-08 17:12:05 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
2019-01-25 15:27:20 +01:00
|
|
|
MMMatrixOut::write(const std::string &fname, const GeneralMatrix &m)
|
2019-01-08 17:12:05 +01:00
|
|
|
{
|
2019-01-25 15:27:20 +01:00
|
|
|
std::ofstream fd{fname, std::ios::out | std::ios::trunc};
|
|
|
|
if (fd.fail())
|
|
|
|
throw MMException("Cannot open file "+fname+" for writing\n");
|
|
|
|
|
|
|
|
fd << "%%%%MatrixMarket matrix array real general" << std::endl
|
2019-04-16 12:40:50 +02:00
|
|
|
<< m.nrows() << ' ' << m.ncols() << std::endl
|
2019-01-25 15:27:20 +01:00
|
|
|
<< std::setprecision(35);
|
2019-04-16 12:40:50 +02:00
|
|
|
for (int i = 0; i < m.ncols(); i++)
|
|
|
|
for (int j = 0; j < m.nrows(); j++)
|
2019-01-25 15:27:20 +01:00
|
|
|
fd << std::setw(40) << m.get(i, j);
|
|
|
|
fd.close();
|
2019-01-08 17:12:05 +01:00
|
|
|
}
|