我有一个mxn
矩阵,其中包含E
个非零元素。非零的坐标已在Ex2
向量中可用。
我想检查每对非零元素之间的最小欧几里德距离是否至少为d
。如果不是这种情况,我想通过归零一些元素来强制执行它(确切地说哪些元素无关紧要)。
在Matlab中有一种优雅的方式吗?
答案 0 :(得分:2)
现在有很多有效的方法来解决这个问题。选择正确的数据将取决于数据的实际性质以及您希望用来细化数据的逻辑。
一种相当简单的方法是扩展每个非零元素,使单个“像素”变为半径为d
的圆。然后,任何彼此太靠近的像素将通过它们的连接圆圈显而易见。
E = rand(100)<0.001; % dummy boolean data
d = 6;
E_dilated = imdilate(E, strel('disk', d, 0));
E_dilated_labeled = bwlabel(E_dilated);
E_labeled = E_dilated_labeled;
E_labeled(~E) = 0;
你从这里做的正是取决于你。如果你真的无法解决如何完成它,那么在评论中发帖。
其他方法可能会使用bwmorph
,bwdist
,watershed
,delaunay
triangulation,甚至k-means或agglomerative hierarchical clustering中的一项或多项,或完全不同的东西。
考虑到这一点,如果将非零条目视为地图上的标记,则此问题在地图应用程序中相当常见。 Google Maps API提供了long page关于他们提供的各种选项的信息。
使用以下额外代码生成图表:
subplot(3,1,1);
imshow(ind2rgb(E, gray(2))); axis image
title('E (as Boolean)');
subplot(3,1,2);
im = ind2rgb(E_dilated_labeled, lines(max(E_dilated_labeled(:)+1)));
im(repmat(~E_dilated_labeled, [1,1,3])) = 0;
imshow(im); axis image;
title('E\_dilated\_labeled');
subplot(3,1,3);
im = ind2rgb(E_labeled, lines(max(E_labeled(:)+1)));
im(repmat(~E_labeled, [1,1,3])) = 0;
imshow(im); axis image;
title('E\_labeled');
答案 1 :(得分:0)
% Initialise the constants
d = 0.1; % Distance Threshold
E = rand(20,2); % Random Mx2 matrix of x and y coordinates
% Display initial matrix
fig1 = figure;
Ex = E(:,1);
Ey = E(:,2);
scatter(Ex, Ey);
% Repeat each coordinate to form a square matrix
ExRep = repmat(Ex, 1, length(Ex));
EyRep = repmat(Ey, 1, length(Ey));
% Calculate the distance between every set of points
distX = ExRep - ExRep';
distY = EyRep - EyRep';
distAll = sqrt(distX.^2 + distY.^2);
% Display the distance between every set of points
figure;
imagesc(distAll);
colormap('gray')
title('Grid of distance from each points');
% Find the points that are at less then a certain distance
smallDist = distAll < d;
figure;
imagesc(smallDist);
colormap('gray')
title('Grid of points with small distance neighbour');
% Find the points with no near neighbours
numNearNeighbour = (sum(smallDist) - 1);
noNearNeighbour = numNearNeighbour == 0;
E2 = E;
E2(noNearNeighbour, :) = [];
% Display the new matrix
figure(fig1);
hold all;
Ex2 = E2(:,1);
Ey2 = E2(:,2);
scatter(Ex2, Ey2, 'marker', '*');
legend({'all points', ['points with neighbours distance < ' num2str(d)]}, 'location', 'northoutside');
hold off;