How to delete consecutive values in a vector and to save the central one?

조회 수: 2 (최근 30일)
CaG
CaG 2018년 7월 7일
댓글: CaG 2018년 7월 11일
I have a vector of increasing values. I want to create a second vector that contains all the "single" numbers and, if I have consecutive numbers, contains only the central value (rounded down, if it is the case).
For example, if I have the vector a=[10 15 16 17 18 19 31 32 37], the final vector should be b=[10 17 31 37].
Unluckily I am not able to find a way to solve this problem. Any ideas?
Thank you in advance for your help.

채택된 답변

Image Analyst
Image Analyst 2018년 7월 7일
Sounds like homework but since you didn't tag it as homework, here's my solution:
a=[10 15 16 17 18 19 31 32 37]
da = [2, diff(a)]
startingIndexes = [find(da ~= 1), length(da)+1]
groupIndex = 1;
for k = 1 : length(startingIndexes)-1
index1 = startingIndexes(k);
index2 = startingIndexes(k+1) - 1;
output(groupIndex) = floor(median(a(index1 : index2))); % Get median of this group.
groupIndex = groupIndex + 1;
end
output
I'm sure there are other ways, perhaps more compact and cryptic, but this seems intuitive and easy for a beginner to follow.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by