필터 지우기
필터 지우기

Remove repeated numbers in series

조회 수: 7 (최근 30일)
Eric
Eric 2019년 4월 7일
편집: madhan ravi 2019년 4월 12일
Hi everyone,
I have a sequence of number like
x = [3 3 3 3 3 2 2 2 2 2 2 2 1 1 1 1 3 3 3 3 3 3];
And I would like to reduce it to be:
x = [3 2 1 3];
Does anyone know how to do that?
Thanks a lot,
Eric

답변 (2개)

Star Strider
Star Strider 2019년 4월 7일
Try this:
x = [3 3 3 3 3 2 2 2 2 2 2 2 1 1 1 1 3 3 3 3 3 3];
dx = diff([0 x]);
fx = find(dx ~= 0);
Result = x(fx)
producing:
Result =
3 2 1 3
Note: This works here, and may not scale up to other problems.
  댓글 수: 2
Stephen23
Stephen23 2019년 4월 8일
편집: Stephen23 2019년 4월 8일
Note that this code will not work if the first value happens to be zero. This bug is easy to fix by prepending a logical value after diff (rather than prepending a fake data value before diff). It is also easy get rid of the superfluous find as well:
>> x = [0 0 0 3 3 3 3 3 2 2 2 2 2 2 2 1 1 1 1 3 3 3 3 3 3];
>> y = x([true,diff(x)~=0])
y =
0 3 2 1 3
Star Strider
Star Strider 2019년 4월 12일
@Stephen —
Noted. Thank you.

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


madhan ravi
madhan ravi 2019년 4월 8일
편집: madhan ravi 2019년 4월 12일
Try this:
ii = [find(x(1:end-1) ~= x(2:end)) numel(x)];
l = diff([0 ii]); % just as a bonus but can be neglected if your not interested how many times the number appears consecutively
u = x(ii)
  댓글 수: 2
Stephen23
Stephen23 2019년 4월 8일
What is l used for?
madhan ravi
madhan ravi 2019년 4월 8일
Ah , it’s not needed but it gives the number of consecutive times the number appears in a sequence.

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

카테고리

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