![]() Registered Member ![]()
|
What is a simple, efficient way to iterate over the coefficients of an array (or matrix)? I have not yet found functions like begin() and end() as you would see in STL. I know I can write nested loops, but that would be less simple and sometimes less efficient than what I want.
|
![]() Registered Member ![]()
|
What kind of matrices are that , are they sparse?
There exist indeed an iterator but it has to be defined before use. |
![]() Registered Member ![]()
|
Here is an example, where I am trying to extract all non-zero elements of a 2D array, producing a 1D destination array. I think it works, but I don't like it. I get a warning on the count function. And it will be unnecessarily slow if handling a row-major src array (after I change it to a DenseBase-based template).
void ExtractNonZeros( const Eigen::ArrayXXf & src, Eigen::ArrayXf & dest ) { auto nnz = src.count(); dest.resize( nnz ); size_t count = 0; for( auto col=0; col < src.cols(); ++col ) { for( auto row=0; row < src.rows(); ++row ) { if( src( row, col ) != 0 ) dest( count++ ) = src( row, col ); } } ASSERT( count == nnz ); } |
![]() Registered Member ![]()
|
What are the dimensions of you matrix?
You should also consider the time for processing count() and that you read twice the matrix. Maybe it's faster to store the result in a temporary variable, this depends on the reading costs. ![]() |
![]() Registered Member ![]()
|
I am looking for a simple way to iterate over elements of a potentially large 2D array, without writing the nested loops. I am primarily interested in dense arrays, but sparse arrays are also worth thinking about.
|
![]() Registered Member ![]()
|
For sparse there exist exemplary documented iterators.
A vector is processed with: --------------------------------------------- SparseVector<double> vec(size); for (SparseVector<double>::InnerIterator it(vec); it; ++it) { it.value(); // == vec[ it.index() ] it.index(); } --------------------------------------------- for a matrix try: --------------------------------------------- SparseMatrix<double> mat(rows,cols); for (int k=0; k<mat.outerSize(); ++k) for (SparseMatrix<double>::InnerIterator it(mat,k); it; ++it) { it.value(); it.row(); // row index it.col(); // col index (here it is equal to k) it.index(); // inner index, here it is equal to it.row() } |
![]() Registered Member ![]()
|
I think my question was not a good one. I missed the following sentence in the documentation:
"Note that the syntax m(index) is not restricted to vectors, it is also available for general matrices, meaning index-based access in the array of coefficients." |
![]() Moderator ![]()
|
Right, so the single for loop is:
for(std::size_t i; i<src.size(); ++i) if(src(i)!=0) dest(count++) = src(i); |
Registered users: Bing [Bot], claydoh, Google [Bot], rblackwell, Yahoo [Bot]