我经常要使用循环,例如:
//Preparing a self contained example:
int m=10,n1=2*m,n2=4*m;
VectorXf a3=VectorXf::Random(n2);
VectorXf x(n1);
VectorXi iS(m);
for(int i=0;i<m;i++)
iS(i)=rand()%n2;
std::cout << "old x" << std::endl;
std::cout << x(0) << std::endl;
//this is the loop I want to find a better alternative to:
for(int i=0;i<m;i++)
x(i)=a3(iS(i));
std::cout << "new x" << std::endl;
std::cout << x(0) << std::endl;
std::cout << "same as" << std::endl;
std::cout << a3(iS(0)) << std::endl;
我想知道是否有更好的方法来执行此循环
- x(i)=a3(iS(i))
的那个 - 使用本征。
编辑:为了使问题更加清晰,我已经完成了示例。
答案 0 :(得分:0)
这样做的正确方法(更清洁,更快)是使用Eigen::Map。你可以这样做:
Eigen::Map<Eigen::VectorXi>x(iS.data(),iS.size());
您也可以对数组使用相同的语法。
OP更新问题后:
在一般情况下,当您想要将Eigen
对象的一部分(例如矩阵)分配给另一个Eigen对象时,您可以使用block操作:
作为一个例子:
Eigen::MatrixXf m(4,4);
m << 1 , 2 , 3 , 4,
5 , 6 , 7 , 8,
9 , 10, 11, 12,
13, 14, 15, 16;
cout<<m.block<2,2>(0,1)<<std::endl;
打印
5 , 6
9 , 10
您也可以使用此语法进行分配:
//Block of size (p,q), starting at (i,j)
matrix.block<p,q>(i,j) = another matrix.block<p,q>(k,l)
对于你的数据没有按顺序存储的特殊问题(即有一个随机索引向量),我担心你的循环就像它得到的一样好。您可以在 igl here和here或mrpt项目中找到相应内容。他们有一个plugin的特征。