在 Matlab 中找到离拟合线及其邻域最近的点

find nearest point to a fitting line and the neighborhood of it in Matlab

假设我有两个随机双精度数组,这意味着一个 x 坐标可能有多个 y 值。

X = randi([-10 10],1,1000); 
Y = randi([-10 10],1,1000);

那我给出一个直线方程:y=ax+b

我想根据每一个x点,找到离直线最近的点的最近点。当我找到这个点时,我会找到它在特定范围内的邻域点。请原谅我糟糕的英语,也许下面的图片可以帮助更多。

因为我有很多数据点,所以我希望有一个有效的方法来处理这个问题。

如果您的 X 是离散的,您可以尝试类似的方法:

xrng = [-10 10];
yrng = [-10 10];
a = rand;
b = rand;
f = @(x) a*x + b;
X = randi(xrng,1,1000);
Y = randi(yrng,1,1000);
ezplot(f,xrng);
hold on;
plot(X,Y,'.');
xx = xrng(1):xrng(2);
nbrSz = 2;
nx = diff(xrng);
nearestIdx = zeros(nx,1);
nbrIdxs = cell(nx,1);
for ii = 1:nx
    x = xx(ii);
    y = f(x);
    idx = find(X == x);
    [~,idxidx] = min(abs(y - Y(idx)));
    nearestIdx(ii) = idx(idxidx);
    nbrIdxIdxs = abs(Y(nearestIdx(ii)) - Y(idx)) <= nbrSz;
    nbrIdxs{ii} = idx(nbrIdxIdxs);
    plot(X(nearestIdx(ii)),Y(nearestIdx(ii)),'og');
    plot(X(nearestIdx(ii)) + [0 0],Y(nearestIdx(ii)) + [-nbrSz nbrSz],'g')
    plot(X(nbrIdxs{ii}),Y(nbrIdxs{ii}),'sy')
end