假設我有如何從Eigen中的索引矢量中提取(Eigen :: Vector的)子矢量?
Eigen :: VectorXd x; // {1,2,3,4,5,6,7,8}
和
徵:: VectorXd ind_vec; // {0,2,4,5}
有沒有一種簡單的方法來提取x的ind_vec元素?
是這樣的: x.extract(ind_vec)返回{1,3,5,6}
感謝。
假設我有如何從Eigen中的索引矢量中提取(Eigen :: Vector的)子矢量?
Eigen :: VectorXd x; // {1,2,3,4,5,6,7,8}
和
徵:: VectorXd ind_vec; // {0,2,4,5}
有沒有一種簡單的方法來提取x的ind_vec元素?
是這樣的: x.extract(ind_vec)返回{1,3,5,6}
感謝。
好像它會很容易寫自己,如果它只是載體:
#include "Eigen/Core"
template <typename T, typename T2>
T extract(const T2& full, const T& ind)
{
int num_indices = ind.innerSize();
T target(num_indices);
for (int i = 0; i < num_indices; i++)
{
target[i] = full[ind[i]];
}
return target;
}
int main()
{
Eigen::VectorXd full(8);
full << 1, 2, 3, 4, 5, 6, 7, 8;
Eigen::Vector4d ind_vec(4);
ind_vec << 0, 2, 4, 5;
std::cout << "full:" << full<< std::endl;
std::cout << "ind_vec:" << ind_vec<< std::endl;
std::cout << "extracted" << extract(full,ind_vec) << std::endl;
}
這應該在大多數情況下
工作編輯:的情況下,你的指數標類型是不同的比你的源和目標標量類型,以下將工作(對於所有內置的特徵類型)。
template <typename T, typename T2>
Eigen::Matrix<typename T2::Scalar,T::RowsAtCompileTime,T::ColsAtCompileTime,T::Options>
extract2(const Eigen::DenseBase<T2>& full, const Eigen::DenseBase<T>& ind)
{
using target_t = Eigen::Matrix < T2::Scalar, T::RowsAtCompileTime, T::ColsAtCompileTime, T::Options > ;
int num_indices = ind.innerSize();
target_t target(num_indices);
for (int i = 0; i < num_indices; i++)
{
target[i] = full[ind[i]];
}
return target;
}
(這就是不同之處在於,另外一個你可以使用整數的向量作爲索引,併兼作源的載體,並獲得雙打的矢量返回INTS的載體,而不是作爲extract()
上面會)
謝謝!我猜這是最有效的方法。雖然我不知道這是在Matlab的子矢量抽取中幕後做了什麼: 像x [[1,2,4,8]]。它是否像你的解決方案一樣通過1,2,4,8的循環或更有效的東西? – user1526533 2014-10-09 05:41:06
@ user1526533,Matlab與C++不同。 – CroCo 2014-10-09 22:00:05
由於當前的答案對我而言並不令人滿意,所以我搜索了一下,在Eigen文檔中找到了this tutorial。
#include <Eigen/Dense>
#include <iostream>
using namespace std;
int main()
{
Eigen::ArrayXf v(6);
v << 1, 2, 3, 4, 5, 6;
cout << "v.head(3) =" << endl << v.head(3) << endl << endl;
cout << "v.tail<3>() = " << endl << v.tail<3>() << endl << endl;
v.segment(1,4) *= 2;
cout << "after 'v.segment(1,4) *= 2', v =" << endl << v << endl;
}
將輸出:
v.head(3) =
1
2
3
v.tail<3>() =
4
5
6
after 'v.segment(1,4) *= 2', v =
1
4
6
8
10
6
我還沒有與向量測試,但我想應該是可能的。
有沒有比直接指定索引容易的事情?你有元素和它們的索引。你還想要什麼? – CroCo 2014-10-09 21:57:26