[英]C++ Armadillo: nearest neighbour
I'm using C++ with the Armadillo library. 我在Armadillo库中使用C ++。
Suppose I have anx 1 column matrix which is sorted in numerical order. 假设我有一个按数字顺序排序的ax 1列矩阵。 For example
例如
mat X; X.randn(100,1);
mat X_sorted; X_sorted = sort(X);
cout << X_sorted << endl;
and suppose I have a variable 并假设我有一个变量
double y = 0.5;
What I want: is a way of finding the index, z
, of x_sorted
, for which x_sorted(z)
is closest to y. 我想要的是:一种找到
x_sorted
的索引z
的x_sorted
,其中x_sorted(z)
最接近 y。 In the case of a tie (which doesn't actually matter in my case), simply choose the larger one. 如果是领带(对我而言实际上并不重要),只需选择较大的领带即可。
One way of doing it is like this: 一种方法是这样的:
int z = as_scalar(sort_index(abs(X_sorted - y)).row(0));
Please feel free to criticise this solution and suggest an improvement. 请随时批评此解决方案并提出改进建议。
Here's an example program of it in action: 这是运行中的示例程序:
int main(int argc, char** argv)
{
using namespace arma;
using namespace std;
mat X; X.randn(100,1);
mat X2; X2.zeros(100,1);
for(int i=0; i<100; i++){X2(i) = i;}
mat X_sorted; X_sorted = sort(X);
mat XX; XX=join_rows(X2,X_sorted);
cout << XX << endl;
double y = 0.5;
int z = as_scalar(sort_index(abs(X_sorted - y)).row(0));
mat XX_z; XX_z = XX.row(z);
cout << XX_z << endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.