필터 지우기
필터 지우기

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

조회 수: 17 (최근 30일)
I have a vector like: a=[1 2 3 7 10 11 12]. The idea that i want to implement is: if I have consecutive numbers (in this situation) 1 2 3 and 10 11 12 to save just the biggest one and still to not delete the "7". So it should become: a=[3 7 12].
My code (it doesnt work properly and gives me error also):
a=[1 2 3 7 10 11 12]
k=numel(a);
for n=2:k
if a(n)==(a(n-1)+1)
a(n)=[];
end
end

채택된 답변

Stephen23
Stephen23 2016년 9월 1일
편집: Stephen23 2016년 9월 1일
If the sequences are integer and increasing only:
>> a = [1,2,3,7,10,11,12];
>> x = [diff(a)~=1,true];
>> a(x)
ans =
3 7 12
  댓글 수: 3
Brian
Brian 2019년 9월 18일
If anyone comes across this and is having issues ("horzcat" error) using vertically orientied data as I was, just transpose the array inside of the diff function. For example:
>> a = [1;2;3;7;10;11;12]
>> x = [diff(a')~=1,true];
>> a(x)
ans =
3
7
12
Stephen23
Stephen23 2019년 9월 19일
@Brian: it is simpler and more efficient to just concatenate along the first dimension:
>> x = [diff(a)~=1;true];
>> a(x)
ans =
3
7
12

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by