How to remove duplicates in an array

조회 수: 2 (최근 30일)
MKN
MKN 2013년 7월 2일
Ex: In the array x=[1 2 2 3 3 3 4 5], i want to eliminate all repeating elements (2,3) and retain non-repeating elements (1,4,5)
i.e., If x=[1 2 2 3 3 3 4 5], answer should be x=[1 4 5]

채택된 답변

Octa
Octa 2013년 7월 2일
편집: Octa 2013년 7월 2일
>> x=[1 2 2 3 3 3 4 5];
>> y = zeros(size(x));
>> for i = 1:length(x)
y(i) = sum(x==x(i));
end
>> for i=length(y):-1:1
if(y(i)>=2)
x(i)=[];
end
end
And your output will be
>>x
1 4 5
  댓글 수: 1
Jan
Jan 2013년 7월 2일
@Octa: Please do not post solutions of homework questions. Reducing the size of an array iteratively has a bad performance. An efficient and more matlabish approach for the 2nd loop:
x = x(x >= 2);

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

추가 답변 (2개)

Image Analyst
Image Analyst 2013년 7월 2일
Sounds like homework. As hints, I'd probably use max() to find the greatest integer and the histogram edges, histc() to get the counts, and ismember() to help with removal. It's just a few lines of code - see if you can do it.

Jan
Jan 2013년 7월 2일
You can also SORT the values at first and obtain the sorting index as 2nd output. Then use DIFF to find equal elements. Finally you can remove them and restore the original order by using the sorting index.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by