数组x和y中的元素是浮点数。我想在arrayx中找到尽可能接近arrayy中的元素(对于arrayy中的每个值-arrayx中的一个元素)。同样,arrayx包含大约10^6个元素,数组y大约为10^3,这是for循环的一部分,因此最好快速完成。在
我试图避免把它作为一个新的for循环,所以我这样做了,但是对于一个大的y数组来说,这是非常慢的
x = np.array([0, 0.2, 1, 2.4, 3, 5]); y = np.array([0, 1, 2]);
diff_xy = x.reshape(1,len(x)) - y.reshape(len(y),1);
diff_xy_abs = np.fabs(diff_xy);
args_x = np.argmin(diff_xy_abs, axis = 1);
x_new = x[args_x]
我是Python新手,所以欢迎任何建议!在
它是以x和y的顺序为代价的,但是这些代码是否满足您的性能需求?Rem:x中的相同值可以用于y的多个值
下面给出了期望的结果。在
最后,使用^{cd2}
也许对较大的数组进行排序,然后从中对较小数组的值进行二进制搜索,如果找到的是最接近的值,并且在附近的索引中相邻的值;如果找不到,则最接近的值将紧靠故障点。在
相关问题 更多 >
编程相关推荐