本文介绍了c ++:Eigen Library新手排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不能为我的生活找出为什么这不工作正常。它似乎没有返回第k个元素。

  typedef Eigen :: Matrix< double,Eigen :: Dynamic,Eigen: :Dynamic>矩阵; 

double test(matrix& D,int k)
{
auto d = D.row(1);
std :: nth_element(d.data(),d.data()+ k,d.data()+ d.size());
return d(k);
}

我也试过了

  template< typename ScalarType,typename Derived> 
void Sort(Eigen :: MatrixBase< Derived>& xValues)
{
std :: sort(xValues.derived()。data(),xValues.derived )+ xValues.derived()。size());
}


double test(matrix& D,int k)
{
auto d = D.row(1);
Sort< double>(d);
return d(k);
}

任何帮助非常感激。



编辑:



我刚刚尝试更改

  auto d = D.row(1); 

  Eigen :: VectorXd rowD = D.row(1); 
....

似乎工作正常。

$ b

解决方案

特征矩阵。这意味着,一个矩阵的行不是一个连续的C数组,你不能使用数据指针作为迭代器。



例如,一个3x4的矩阵将被存储as:

 
0 3 6 9
1 4 7 10
2 5 8 11

 

现在 row(1)将是

 
1 4 7 10

但是传递给 nth_element的指针迭代器()将访问

 
1 2 3 4

如果您将矩阵 typedef更改为row-major:



<$> p $ p> typedef Eigen :: Matrix< double,Eigen :: Dynamic,Eigen :: Dynamic,Eigen :: RowMajor>矩阵;






更新:编辑示例的工作原理,因为您行复制到一个向量。对于向量(一维矩阵),无论数据是以行为主还是列为主。


I can't for the life of me work out why this isn't working correctly. It doesn't seem to return the kth element.

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix;

double test(matrix& D, int k)
{
    auto d = D.row(1);
    std::nth_element(d.data(),d.data()+k, d.data()+d.size());
    return d(k) ;
}

I have also tried

template <typename ScalarType, typename Derived>
void Sort(Eigen::MatrixBase<Derived> &xValues)
{
std::sort(xValues.derived().data(), xValues.derived().data()+xValues.derived().size());
}


double test(matrix& D, int k)
{
    auto d = D.row(1);
    Sort<double>(d);
    return d(k) ;
}

Any help much appreciated.

Edit:-

I have just tried changing

auto d = D.row(1);

to

Eigen::VectorXd rowD = D.row(1);
....

and it seems to work ok.

Slightly confused by that.

解决方案

Eigen matrices are column-major per default. That means, that a row of a matrix is not a contiguous C array and you cannot use the data pointer as an iterator.

For example, a 3x4 matrix would be stored as:

0 3 6  9
1 4 7 10
2 5 8 11

Now, row(1) would be

1 4 7 10

But the pointer iterator you are passing to nth_element() will access

1 2 3 4

Your code works if you change your matrix typedef to row-major:

typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> matrix;


Update: Your edited example works since you copy the row to a vector. For vectors (one-dimensional matrices), it does not matter if the data is stored row-major or column-major.

这篇关于c ++:Eigen Library新手排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 17:12