vendredi 27 mars 2015

Writing a Boost ublas matrix to a text file

I have a Boost ublas matrix, and I want to print its contents to a text file. I have the following implementation, and it works.



#include <iostream>
using namespace std;
#include "boost\numeric\ublas\matrix.hpp"
typedef boost::numeric::ublas::matrix<float> matrix;
#include <algorithm>
#include <iterator>
#include <fstream>

int main()
{
fill(m1.begin2(), m1.begin2() + 400 * 500, 3.3);

ofstream dat("file.txt");
for (auto i = 0; i < 400 ; i++) {
for (auto j = 0; j < 500; j++) {
dat << m1(i, j) << "\t"; // Must seperate with Tab
}
dat << endl; // Must write on New line
}


I want to write this code without using the nested for loops. I tried the ostreambuf_iterator API as follows



copy(m1.begin2(), m1.begin2() + 500 * 400, ostream_iterator<float>(dat, "\n")); // Can only new line everything


However, as you can see, successive elements were written on new line, and I was not able to achieve the type of sequencing as I did with nested for loop. Is there a way to do what I did inside the nested for using an STL algorithm?


Aucun commentaire:

Enregistrer un commentaire