gpt4 book ai didi

C++ Armadillo : nearest neighbour

转载 作者:太空宇宙 更新时间:2023-11-04 11:26:01 31 4
gpt4 key购买 nike

我将 C++ 与 Armadillo 库结合使用。

假设我有一个按数字顺序排序的 n x 1 列矩阵。例如

mat X; X.randn(100,1);
mat X_sorted; X_sorted = sort(X);
cout << X_sorted << endl;

假设我有一个变量

double y = 0.5;

我想要的: 是一种找到 x_sorted 的索引 z 的方法,其中 x_sorted(z) 最接近 y。如果是领带(这对我来说并不重要),只需选择较大的领带即可。

最佳答案

一种方法是这样的:

int z = as_scalar(sort_index(abs(X_sorted - y)).row(0));

请随时批评此解决方案并提出改进建议。

这是一个实际的示例程序:

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;
}

关于C++ Armadillo : nearest neighbour,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659726/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com