How can i find the elements of an array with in tolerance and map them to a unique number if those number are within that tolerance?
10 次查看(过去 30 天)
显示 更早的评论
Hi every one
i have an array A=[0.5 1 1.75 2 5 5.25 5.75 6 6.25 9 9.25 9.5 10.25], now i want to find elements of this array that are closer than (A(i)-A(j)<2) to each other and map them to an array such M=[1 1 1 1 2 2 2 2 2 3 3 3 3] in which for example the elements 0.5, 1, 1.75 and 2 are all maped to 1 in the array M. can enyone please help me with this?
thank you
0 个评论
采纳的回答
Guillaume
2019-1-18
编辑:Guillaume
2019-1-18
This requires the image processing toolbox (for bwlabel). It also requires that A is sorted (which appears to be the case in your example). Finally, note that the following will also group together [1 2 3 4] since the difference between consecutive numbers is < 2 even the the difference between the extreme is > 2. If you don't want that then you need to explain how the numbers should be grouped in that case.
A=[0.5 1 1.75 2 5 5.25 5.75 6 6.25 9 9.25 9.5 10.25];
assert(issorted(A), 'A must be sorted');
result = diag(bwlabel(abs(A - A.') <= 2, 4)).'
edit: Actually, it can be done easily without the image processing toolbox. The same conditions still apply:
A=[0.5 1 1.75 2 5 5.25 5.75 6 6.25 9 9.25 9.5 10.25];
assert(issorted(A), 'A must be sorted');
result = cumsum([1, diff(A) > 2])
0 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!