Firstly, Eigen's resize
method reallocates memory if the new number of elements is not the same as the old, both when growing and when shrinking, so you would lose data in this case
The following method uses .head<int>()
, which is Eigen3's version of .start<int>()
, plus some template programming so you don't have to check whether you're shrinking or growing:
#include <Eigen/Core>
template <bool COND, int A, int B>
struct IF
{
enum { val = A };
};
template <int A, int B>
struct IF<false, A, B>
{
enum { val = B };
};
template <int A, int B>
struct MIN : IF<A < B, A, B>
{
};
template <typename T,int dim,int newDim>
Eigen::Matrix<T,newDim,1> to(Eigen::Matrix<T,dim,1> p)
{
Eigen::Matrix<int,newDim,1> newp =
Eigen::Matrix<T,newDim,1>::Zero();
newp.template head< MIN<dim,newDim>::val >() =
p.template head< MIN<dim,newDim>::val >();
return newp;
}
Using this, the following program:
#include <iostream>
int main()
{
Eigen::Vector2i p_2i(1,2);
Eigen::Vector3i p_3i(3,4,5);
std::cout << to<int, 2, 3>(p_2i) << std::endl << std::endl;
std::cout << to<int, 3, 2>(p_3i) << std::endl << std::endl;
}
Gives as output:
1
2
0
3
4