how to find closest values in array)

조회 수: 7 (최근 30일)
mona
mona 2017년 6월 17일
답변: Image Analyst 2017년 6월 17일
I want to find closest numbers in array as shown in example a=[4 7 8 9 10 11 20 23 26 27 28 29 30 60] output first group 7 8 9 10 11 second group 26 27 28 29 30
  댓글 수: 3
mona
mona 2017년 6월 17일
I need to automatically detect how many groups there are , each group membership is array and has values that difference between each number and next number is one. array is one dimension
Alex L
Alex L 2017년 6월 17일
Is your array always going to be sorted? To refine your question: You are looking for groups of integers in your array that have an absolute difference of 1 to either the preceding or the following integer in the array?

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2017년 6월 17일
If you have the Image Processing Toolbox, you can use bwlabel to give an "ID number" to each group that has the minimum spacing. Then you can extract each of those labeled groups one at a time and put into a cell array.
a=[4 7 8 9 10 11 20 23 26 27 28 29 30 60] % Original, easy case: separate groups
% a=[4 7 8 9 10 11 12 25 26 27 28 29 30 60] % Tricky test case: groups adjacent/touching
% a=[6 7 8 9 10 11 12 25 26 27 28 29 30 31] % Tricky test case: groups touch each other and ends
diffs = diff(a)
minSpacing = min(diffs)
binaryLabels = diffs == minSpacing
% Label the groups
labeledgroups = bwlabel(binaryLabels)
% Extract each group
for k = 1 : max(labeledgroups)
thisGroupsIndexes = find(labeledgroups == k);
% Tack one more.
thisGroupsIndexes = [thisGroupsIndexes, thisGroupsIndexes(end)+1]
% Extract these elements from the original "a" vector
result{k} = a(thisGroupsIndexes)
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by