Traversing a boost::ublas matrix using iterators

廉价感情. 提交于 2020-01-13 09:17:05

问题


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?


回答1:


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
...


来源:https://stackoverflow.com/questions/26044603/traversing-a-boostublas-matrix-using-iterators

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!