To remove the repeated number

1 visualización (últimos 30 días)
sudha rani
sudha rani el 7 de Feb. de 2013
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 comentario
Jos (10584)
Jos (10584) el 7 de Feb. de 2013
and get rid of the 5 as well?

Iniciar sesión para comentar.

Respuestas (3)

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

Andrei Bobrov
Andrei Bobrov el 7 de Feb. de 2013
% 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 comentario
Jan
Jan el 7 de Feb. de 2013
Very old releases do not know the 'first' flag in the unique() command.

Iniciar sesión para comentar.


Jan
Jan el 7 de Feb. de 2013
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, ...

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by