Removing neighbours that are too close from eachother in a vector
6 views (last 30 days)
Show older comments
Hello,
I am trying to solve a problem in which I have, for example, the following vector:
x = [1 8 9 10 15 20 22 25 34]
And i want the output to be like this:
x = [1 9 15 22 34]
So basically analyzing which values are too close from eachother and removing them, while keeping the "middle" one (the one closest to the average of the points removed).
I've tried with
uniquetol(x], 5, 'DataScale', 1)
But uniquetol() only allows to select the hightest or lowest of the values removed. Any ideas/help are welcomed.
Accepted Answer
Stephen23
on 19 Jan 2023
x = [1,8,9,10,15,20,22,25,34]
[~,~,y] = uniquetol(x, 5, 'DataScale',1);
z = accumarray(y(:),x(:),[],@(v) v(ceil(end/2)))
0 Comments
More Answers (2)
DGM
on 19 Jan 2023
Edited: DGM
on 19 Jan 2023
Here's my guess. The behavior is dependent on whether you can actively accept or reject entries. If it's assumed that values can only be rejected, then:
x = [1 8 9 10 15 20 22 25 34];
%x = [1 9 15 22 34];
wradius = 1; % for a 1x3 window
badrange = 5; % anything less is "too close"
goodvalues = true(size(x));
for k = 1+wradius:numel(x)-wradius
sidx = k-wradius:k+wradius;
sample = x(sidx);
if max(sample)-min(sample) <= badrange
av = mean(sample);
[~,idx] = min(abs(sample-av));
mask = false(1,3);
mask(idx) = true;
goodvalues(sidx) = mask & goodvalues(sidx);
end
end
output = x(goodvalues)
I'm only picking the first value that's "closest" to the mean. If there are ties, it's going to keep the leftmost match.
0 Comments
Image Analyst
on 19 Jan 2023

So in the above diagram from Wikipedia the red and yellow points are all in one cluster because they are all within a certain distance of at least one other point in the cluster. Point N is not in that cluster - it's in it's own cluster because it is not closer than the specified distance from any of the other points.
I'm attaching an example as applied to images but you could apply it to a 1-D numberline like you have. Once you find the clusters, replace each cluster with the mean of the cluster and then remove duplicates.
dbscan is one of the best clustering algorithms and one you should learn about even if you don't see how it can apply here.
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!