필터 지우기
필터 지우기

Removing repeated in order elements from array?

조회 수: 5 (최근 30일)
Nicholas Kavouris
Nicholas Kavouris 2022년 3월 30일
댓글: Voss 2022년 3월 30일
I have an array like [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6]
Is there a method which will produce array [ 1 2 3 1 2 4 5 6] and remove all repeating orderly values but not remove all duplicates?
have tried code below with no luck
for k=length(array):-1:1
if array(k)==array(k+1)
array(k)=[]
end
end

답변 (2개)

Rik
Rik 2022년 3월 30일
No need for a loop (even if you should have replaced length by numel):
data=[ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
L=diff(data)==0; % note: this is 1 element shorter that data itself
data(L)=[]
data = 1×8
1 2 3 1 2 4 5 6

Voss
Voss 2022년 3월 30일
Your approach will work; you just have to start at the second-to-last element instead of the last:
array = [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
for k=length(array)-1:-1:1
if array(k)==array(k+1)
array(k)=[];
end
end
array
array = 1×8
1 2 3 1 2 4 5 6
Here's another approach:
array = [ 1 1 1 2 2 3 3 3 1 1 1 2 2 4 4 4 5 5 6];
array(diff(array) == 0) = [];
array
array = 1×8
1 2 3 1 2 4 5 6
  댓글 수: 3
Torsten
Torsten 2022년 3월 30일
편집: Torsten 2022년 3월 30일
Why not ? I get
array = [2]
It's because diff(array) has one element less than array.
Voss
Voss 2022년 3월 30일
As @Torsten says, it should still work (both ways work):
array = [2 2 2 2 2 2 2];
for k=length(array)-1:-1:1
if array(k)==array(k+1)
array(k)=[];
end
end
array
array = 2
array = [2 2 2 2 2 2 2];
array(diff(array) == 0) = [];
array
array = 2

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

카테고리

Help CenterFile Exchange에서 Data Type Conversion에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by