How to delete consecutive values in a vector and to save the central one?
2 views (last 30 days)
Show older comments
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.
0 Comments
Accepted Answer
Image Analyst
on 7 Jul 2018
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.
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!