Bypassing boost :: ublas macro using iterators

I just want to traverse the matrix from start to finish, touching each element. However, I see that there is no iterator to raise the matrix, but there are two iterators, and I have not been able to figure out how to get them to work so that you can traverse the whole matrix

    typedef boost::numeric::ublas::matrix<float> matrix;

    matrix m1(3, 7);

    for (auto i = 0; i < m1.size1(); i++)
    {
        for (auto j = 0; j < m1.size2(); j++)
        {
            m1(i, j) = i + 1 + 0.1*j;
        }
    }

    for (auto itr1 = m1.begin1(); itr1!= m1.end1(); ++itr1)
    { 
        for (auto itr2 = m1.begin2(); itr2 != m1.end2(); itr2++)
        {
            //std::cout << *itr2  << " ";
            //std::cout << *itr1  << " ";
        }
    }

      

This code of mine only prints row1 of the matrix using itr1 and only column 1 of the matrix using itr2. What can be done to access all rows and columns?

+3


source to share


1 answer


To iterate over a matrix, iterator2 must be retrieved from iterator1, for example:

for(auto itr2 = itr1.begin(); itr2 != itr1.end(); itr2++)

      

Complete code:



#include <stdlib.h>
#include <boost/numeric/ublas/matrix.hpp>

using namespace boost::numeric::ublas;
using namespace std;

int main(int argc, char* argv[]) {

  typedef boost::numeric::ublas::matrix<float> matrix;

  matrix m1(3, 7);
  for (auto i = 0; i < m1.size1(); i++) {
    for (auto j = 0; j < m1.size2(); j++) {
      m1(i, j) = i + 1 + 0.1*j;
    }
  }

  for(matrix::iterator1 it1 = m1.begin1(); it1 != m1.end1(); ++it1) {
    for(matrix::iterator2 it2 = it1.begin(); it2 !=it1.end(); ++it2) {
      std::cout << "(" << it2.index1() << "," << it2.index2() << ") = " << *it2 << endl;
    }
    cout << endl;
  }

  return EXIT_SUCCESS;
}

      

Outputs:

(0,0) = 1
(0,1) = 1.1
(0,2) = 1.2
(0,3) = 1.3
...

      

+7


source







All Articles