Eigen3: Passing fixed size matrix and dynamic size matrix in one data type in template function

StackOverflow https://stackoverflow.com/questions/22650112

  •  21-06-2023
  •  | 
  •  

Question

I have further question continuing my previous question. Now I want to pass two kinds of Eigen parameters in one type: (1) fixed sized matrix or (2) rows is fixed but cols is dynamic. Both matrices's rows always should be 3. Thy modified function is:

template<typename Derived>
typename Derived::PlainObject bar(const Eigen::MatrixBase<Derived>& v)
{
  // EIGEN_STATIC_ASSERT_FIXED_SIZE(Derived);
  // EIGEN_STATIC_ASSERT(Derived::RowsAtCompileTime == 3,
  //                     THIS_METHOD_IS_ONLY_FOR_MATRICES_OF_A_SPECIFIC_SIZE);
  assert(v.rows() == 3);

  typename Derived::PlainObject ret;

  std::cout << "v size  : "   << v.rows() << ", " << v.cols()   << std::endl;
  std::cout << "ret size: " << ret.rows() << ", " << ret.cols() << std::endl;

  return ret;
}

I want to create variable its size is same as the passed parameter v in the function. Passing fixed size matrix is fine, but not for dynamic (column) size matrix. The number of columns of ret for dynamics size matrix is 0.

void main()
{
  int n = 1000;

  Eigen::Matrix<double, 3, Dynamic> A1 = Eigen::Matrix<double, 3, Dynamic>::Random(3, n);
  Eigen::Matrix<double, 3, 1000>    B1 = Eigen::Matrix<double, 3, 1000>::Random();

  Eigen::Matrix<double, 3, Dynamic> A2 = bar(A1);
  Eigen::Matrix<double, 3, 1000>    B2 = bar(B1);
}

Output:

v size  : 3, 1000
ret size: 3, 0
v size  : 3, 1000
ret size: 3, 1000

Is there a consistent way to create variable its size is same as the passed parameter for both of fixed size matrix and dynamic (column) size matrix? Or It is not possible to pass them in one data type?

Thanks in advance!

Was it helpful?

Solution

Since the number of columns is only known at runtime (it's not part of the type), you need to specify it when you create the matrix ret as follow:

template<typename Derived>
typename Derived::PlainObject bar(const Eigen::MatrixBase<Derived>& v)
{
    typename Derived::PlainObject ret(v.rows(), v.cols());

    std::cout << "v size  : "   << v.rows() << ", " << v.cols()   << std::endl;
    std::cout << "ret size: " << ret.rows() << ", " << ret.cols() << std::endl;

    return ret;
}

After this change you get the expected answer in both cases:

v size  : 3, 1000
ret size: 3, 1000
v size  : 3, 1000
ret size: 3, 1000
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top