如何在数组中找到最接近给定数字的值? [英] how do I find the closest value to a given number in an array?

查看:704
本文介绍了如何在数组中找到最接近给定数字的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况如下:

我必须数组,表示一个正域x,另一个数组的功能是该域z

I have to arrays, symbolizing a positive domain x, and another array whose a function of that domain z

现在,对于给定的点y,我希望在最近的位置找到z值.为此,我编写了以下函数:

Now, I want, for a given point y, to find the z value in the nearest location. For thatI wrote the following function:

R0 = @(y) z(find(abs( abs(y). -  r) == min(abs(abs(y). - r))))

(由于z是对称的,因此abs用于负值y)

(The use of abs is for negative values of y, since z is symmetric)

除非y是向量,否则这很好地工作.因此,如果我使用以下代码:

This works perfectally well, unless y is a vector. So, if I use the following code:

y = [-1:0.01:1];
R0(y);

我收到以下错误:

Error using  == 
Matrix dimensions must agree.

尝试调试它,我发现find语句返回了1 * 0矩阵,因此什么也没有.尽管r数组中y的值实际存在.

Trying to debug it, I came to see that the find statement returned a 1*0 matrix, hence nothing. This is although the value of y ACTUALLY EXSIST in the r array.

我真正想要的是获取一个新的向量,该向量为y的每个值分配z中最接近的值.

What I really want is to get a new vector, which assign the nearest value in z for each value of y.

可能会使用其他完全不同的解决方案,因此我更愿意理解为什么该解决方案不起作用以及如何使它起作用.

Other, totally different solutions might be used, so I prefer understanding why this solution doesn't work and how can I make it work.

谢谢

推荐答案

您的问题不是很清楚.如果我理解正确,对于y的每个元素,您都想在z中找到最接近的元素.

Your question is not very clear. If I understand correctly, for each element of y you want to find the closest element in z.

y = [1 2 3 4 5]; %// example data
z = [0 2.5 6]; %// example data
d = abs(bsxfun(@minus, y(:).', z(:))); %'// compute distance for all pairs
[~, ind] = min(d); %// index of minimizer in z for each value of y
result = z(ind);

在此示例中,

result =
        0    2.5000    2.5000    2.5000    6.0000

这篇关于如何在数组中找到最接近给定数字的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆