如何解决如何使用Eigen在Matrix块上构造方便的迭代器
我想构造一个“块向行”迭代器,该迭代器使用本征在Dense Matrix的所有可能块上运行。
#include <iostream>
#include <Eigen/Dense>
int main() {
Eigen::MatrixXd A(4,4);
A << 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;
for (Eigen::Index k=0; k< ? ; ++k) {
//?????
Eigen::Iterator it.... ;
std::cout<<it<<std::endl;
}
}
输出应为:
1 2
5 6
9 10
13 14
3 4
7 8
11 12
15 16
本质上,我正在搜索一个不错的版本
#include <iostream>
#include <Eigen/Dense>
int main() {
Eigen::MatrixXd A(4,16;
int numberOfBlocksPerDir =2;
for (int i = 0; i < numberOfBlocksPerDir ; i++) {
for (int j = 0; j < numberOfBlocksPerDir ; j++) {
Eigen::Block<Eigen::MatrixXd,2> currentBlock = A.block<2,2>(numberOfBlocksPerDir * j,numberOfBlocksPerDir * i);
std::cout<<currentBlock <<std::endl;
}
}
}
使用Eigen内置函数是否可能实现这种效果?如果不是,那么独自完成此操作的好方法是什么? (定义我自己的迭代器?)
解决方法
在Eigen
文档中找不到任何内容,但是简单的正向迭代器并不需要太多内容:
- 平等经营者
- 增量运算符
- 取消引用运算符
这就是我想出的
template <Eigen::Index RowSize,Eigen::Index ColSize>
struct EigenBlockIt {
using Self = EigenBlockIt<RowSize,ColSize>;
// constructors for end()/begin() equivalents
EigenBlockIt() : matrix(nullptr),col(0),row(0) { }
EigenBlockIt(const Eigen::MatrixXd& matrix) : matrix(&matrix),row(0) { }
// comparison
friend bool operator ==(const Self& lhs,const Self& rhs) {
return lhs.matrix == rhs.matrix && lhs.row == rhs.row && lhs.col == rhs.col;
}
friend bool operator !=(const Self& lhs,const Self& rhs) {
return lhs.matrix != rhs.matrix || lhs.row != rhs.row || lhs.col != rhs.col;
}
// increment (postfix/prefix)
Self& operator++() {
row++;
if (row >= matrix->rows() / RowSize) {
row = 0;
col++;
if (col >= matrix->cols() / ColSize) {
matrix = nullptr;
row = 0;
col = 0;
}
}
return *this;
}
Self operator++(int) {
EigenBlockIt it = *this;
++(*this);
return it;
}
// dereference
const Eigen::Block<const Eigen::MatrixXd,RowSize,ColSize> operator *() const {
return matrix->block<RowSize,ColSize>((matrix->rows() / RowSize) * row,(matrix->cols() / ColSize) * col);
}
const Eigen::MatrixXd* matrix;
Eigen::Index row;
Eigen::Index col;
};
用法:
for (auto it = EigenBlockIt<2,2>(A); it != EigenBlockIt<2,2>(); ++it) {
std::cout << *it << std::endl;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。