The two pieces of code below attempt to iterate over the non zero elements of a matrix, both crash. I suspect from looking over the various discussions online that the correct placement of & is critical? Assuming it is possible to create two working examples of BOOST_FOREACH matrix and matrix iterators, which method is preferred / “better” / more efficient? Thanks!

 

#include <boost/foreach.hpp>

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

#include <boost/numeric/ublas/matrix_sparse.hpp>

#include <boost/numeric/ublas/matrix_expression.hpp>

#include <boost/numeric/ublas/matrix_proxy.hpp>

#include <boost/numeric/ublas/vector.hpp>

#include <boost/numeric/ublas/vector_sparse.hpp>

#include <boost/numeric/ublas/vector_expression.hpp>

#include <boost/numeric/ublas/vector_proxy.hpp>

 

boost::numeric::ublas::compressed_matrix<float> M(n,n);

boost::numeric::ublas::compressed_vector<float> v(n);

 

// Example 1: BOOST for each…

// TODO: 2D nested matrix example?

BOOST_FOREACH(float, v)

{

   v += 1; // do something with each non zero element of v…

} // end for each

 

// Example 2: iterators

boost::numeric::ublas::compressed_matrix<u32>::iterator1 i;

boost::numeric::ublas::compressed_matrix<u32>::iterator2 j;

for (i = M.begin1(); i != M.end1(); ++i)

{

   for (j = M.begin2(); j != M.end2(); ++j)

   {

      // use j.index1(), j.index2(), *j to access each non zero element of M

      *j = v(j.index1()); // do something with each non zero element of both matrix and vector…

   } // end for

} // end for

 

Extra credit: I suspect I should protect the code with some kind of assert to ensure the size of vector is the same as the size of matrix.