将MatrixXd
与Array<bool, Dynamic, 1>
切片,就像在Matlab中一样,您可以执行A(A>5)
,在这里您可以执行slice(A, A.array() > 5)
。我想将其转换为模板版本,以便它可以采用任何类型的矩阵或向量,例如Matrix3i
或VectorXi
。该页面告诉我使用MatrixBase<Derived>
,但是我无法使用它。 IDK如何声明一定大小的模板化矩阵。
https://eigen.tuxfamily.org/dox/TopicFunctionTakingEigenTypes.html
#include <Eigen/Dense>
using namespace Eigen;
MatrixXd slice(const MatrixXd & mat, const Array<bool, Dynamic, 1> & ind)
{
assert(mat.cols() == ind.size());
// find out dimensions of the matrix going out
int _cols = 0;
for(int i = 0; i < ind.size(); ++i)
{
if(ind[i] == 1)
{
_cols += 1;
}
}
//populate the matrix going out, in a column major way
int _pos = 0;
MatrixXd out = MatrixXd::Zero(mat.rows(), _cols);
for(int i = 0; i < ind.size(); ++i)
{
if(ind[i] == 1)
{
out.col(_pos) = mat.col(i);
_pos += 1;
}
}
return out;
}
用法如下:
MatrixXd A(4, 4);
A << 1,2,3,4,
5,6,7,8,
1,5,6,3,
9,8,6,5;
VectorXd b(4);
b << 23,-4,1234,3;
cout << A << endl;
cout << (b.array() > 5) << endl;
cout << slice(A, b.array() > 5) << endl;
输出是这样的:
1 2 3 4
5 6 7 8
1 5 6 3
9 8 6 5
1
0
1
0
1 3
5 7
1 6
9 6
如果有人能告诉我该怎么做,我将不胜感激!
PS:文档中似乎有类似的功能:
https://eigen.tuxfamily.org/dox-devel/group__TutorialSlicingIndexing.html
但是我实际上无法在的Eigen / Core中找到关键字all
std::vector<int> ind{4,2,5,5,3};
MatrixXi A = MatrixXi::Random(4,6);
cout << "Initial matrix A:\n" << A << "\n\n";
cout << "A(all,ind):\n" << A(all,ind) << "\n\n";
我的IDE也无法解决它。