To remove the repeated number

조회 수: 1 (최근 30일)
sudha rani
sudha rani 2013년 2월 7일
i have a matrix [1 2 2 2 3 4 5] and i want to get the result has [1 2 3 4] by replacing the repeated 2 by the single number.
  댓글 수: 1
Jos (10584)
Jos (10584) 2013년 2월 7일
and get rid of the 5 as well?

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

답변 (3개)

Brian B
Brian B 2013년 2월 7일
Use
unique([1 2 2 2 3 4 5])
Note that this will also sort the elements.
-B

Andrei Bobrov
Andrei Bobrov 2013년 2월 7일
% without sorting array
m = randi(5,1,10);
[~,ii] = sort(m); % for Jan's solution
jj = [true,diff(m(ii))~=0];
out1 = m(sort(ii(jj)));
out2 = unique(m,'stable'); % in R2012a and later
[u,b] = unique(m,'first'); % old releases
[~,ii] = sort(b);
out3 = u(ii);
  댓글 수: 1
Jan
Jan 2013년 2월 7일
Very old releases do not know the 'first' flag in the unique() command.

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


Jan
Jan 2013년 2월 7일
No sorting, considering only neighboring elements such that e.g. [1,2,1] is not altered:
m = [1 2 2 2 3 4 5];
u = m([true, diff(m) ~= 0]);
You see, there are many different solutions, because your problem is not defined exactly: Sorting, not neighboring repetitions, ...

카테고리

Help CenterFile Exchange에서 Shifting and Sorting Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by