【Matlab】基于KDtree的最近邻搜索和范围搜索

摘要:介绍Matlab的rangesearch()函数和knnsearch()函数。

rangesearch() —— 根据给定k-维数据集,返回指定距离范围内的所有数据点
knnsearch() —— 根据给定k-维数据集,返回最近的K个数据点

%% 给定数值矩阵(input data),返回最近点的K个点
% data matrix,100 x 3,表示100个空间点
data = [hospital.Age, hospital.Weight, 66 * rand(100, 1)];
% 绘制空间点
scatter3(data(:, 1), data(:, 2), data(:, 3), 36, [1 0 0], "filled", "o")
hold on
zlabel 'Z'
% 目标点有两个
targetPoint = [50 162 21; 
    12 180 31];
% 绘制目标点
scatter3(targetPoint(:, 1), targetPoint(:, 2), targetPoint(:, 3), 72, "magenta", "filled", "hexagram")
hold on
tic
% 搜索目标点周围最近的3个点,返回值为data matrix的row index.
id = knnsearch(data, targetPoint, "Distance", "euclidean", "K", 3, "NSMethod", "kdtree");
toc
result = data(reshape(id,[1,6]), :);
% 绘制result 点
scatter3(result(:, 1), result(:, 2),result(:,3), 72, "blue", "filled", "square")

img

%% rangesearch():返回指定距离内的所有行索引
% dataCloud是10维数据,545580个数据点。
data = dataCloud(:,1:3);
% 绘制散点
scatter3(data(:, 1), data(:, 2), data(:, 3), 12, [1 0 0], "filled", "o")
hold on
zlabel 'Z'
targetPoint = [40164.5	139.539	496.914];
% 绘制目标点
scatter3(targetPoint(:, 1), targetPoint(:, 2), targetPoint(:, 3), 36, "magenta", "filled", "hexagram")
hold on
tic
% knn search using input data,直接给定数据集,搜索半径为50
id = rangesearch(data(:, 1 : 3), targetPoint, 50, "NSMethod", "kdtree", "Distance", "euclidean");
toc
result = data(id{1}, :);
% 绘制result 点
scatter3(result(:, 1), result(:, 2), result(:, 3), 72, "blue", "filled", "square")

img

%% 先创建KDtree model ,以此为基础返回范围内的点
data = dataCloud;
% 绘制散点
scatter3(data(:, 1), data(:, 2), data(:, 3), 12, [1 0 0], "filled", "o")
hold on
zlabel 'Z'
targetPoint = [40235.1142325237	-128.940013761462	738.5117255760920];
% 绘制目标点
scatter3(targetPoint(:, 1), targetPoint(:, 2), targetPoint(:, 3), 36, "magenta", "filled", "hexagram")
hold on

mdl = KDTreeSearcher(data(:, 1 : 3), "Distance", 'euclidean');
tic
% knn search using KDtree model,直接给定数据集,搜索半径为50
id = rangesearch(mdl, targetPoint, 50, "Distance", "euclidean");
toc
result = data(id{1}, :);
% 绘制result 点
scatter3(result(:, 1), result(:, 2), result(:, 3), 72, "blue", "filled", "square")

img

posted @ 2023-07-30 15:53  FE-有限元鹰  阅读(680)  评论(0编辑  收藏  举报