Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a boost::ublas matrix using iterators

I simply want to traverse a matrix from start to finish touching upon every element. However, I see that there is no one iterator for boost matrix, rather there are two iterators, and I haven't been able to figure out how to make them work so that you can traverse the entire 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, prints only row1 of matrix using itr1 and only column1 of the matrix using itr2. What can be done to instead access all rows and columns?

like image 614
The Vivandiere Avatar asked Sep 25 '14 17:09

The Vivandiere


1 Answers

To iterate over the matrix, iterator2 should be fetched from iterator1, like this:

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

Full 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
...
like image 168
Grigorii Chudnov Avatar answered Oct 19 '22 07:10

Grigorii Chudnov