Borrar filtros
Borrar filtros

In a sorted vector ,how do I compare first element to other elements and then find if there are any duplicates , if yes take their indexes and replace it with 0

6 visualizaciones (últimos 30 días)
A = [ 1, 1 , 2, 3, 4]
I want to first compare first element to all other elements, if there is any duplicate (like 1, 1 in this example) I need to replace it with 0.

Respuesta aceptada

Stephen23
Stephen23 el 6 de Nov. de 2018
Editada: Stephen23 el 6 de Nov. de 2018
For a sorted row vector. Find duplicates of the first element, as you requested:
>> A = [1,1,2,3,4];
>> X = A(1)==A;
>> X(1) = false;
>> A(X) = 0
A =
1 0 2 3 4
Or perhaps you meant to find all duplicates, not just of the first element:
>> A = [1,1,2,3,4];
>> X = [false,diff(A)==0];
>> A(X) = 0
A =
1 0 2 3 4
  19 comentarios
Stephen23
Stephen23 el 15 de Nov. de 2018
Editada: Stephen23 el 15 de Nov. de 2018
PS: taking a wild guess here, that you want to perform this for each page (i.e. along the third dimension) independently:
>> C = {[9,3,7;6,3,8;3,7,9],[8,4,8;2,6,7;2,9,5]};
>> A = cat(3,C{:})
A(:,:,1) =
9 3 7
6 3 8
3 7 9
A(:,:,2) =
8 4 8
2 6 7
2 9 5
>> DM = sort(sort(A,1),2)
DM(:,:,1) =
3 3 7
3 6 8
7 9 9
DM(:,:,2) =
2 4 5
2 6 7
8 8 9
>> X = DM(1,1,:)==DM;
>> [~,~,P] = ind2sub(size(X),find(X));
>> V = accumarray(P,1,[],@(v)1/sum(v));
>> A(X) = V(P);
>> A(~X) = 0
A(:,:,1) =
0.33333 0.33333 0.00000
0.33333 0.00000 0.00000
0.00000 0.00000 0.00000
A(:,:,2) =
0.50000 0.00000 0.00000
0.50000 0.00000 0.00000
0.00000 0.00000 0.00000
If that is not the output that you expect then please show me what output you need to get.
Sagar  Saxena
Sagar Saxena el 15 de Nov. de 2018
Thanks Stephen, This works perfectly fine for what I need and you are right instead of using dimension I should be using the term page. Let me try puting this peice of logic into my actual code. Will let you know if I am stuck any further.
But this really helped, Thanks a lot!

Iniciar sesión para comentar.

Más respuestas (3)

TADA
TADA el 5 de Nov. de 2018
Editada: TADA el 5 de Nov. de 2018
how about unique(A)?

madhan ravi
madhan ravi el 6 de Nov. de 2018
Editada: madhan ravi el 6 de Nov. de 2018
A = [ 1, 1, 2, 3, 4];
[~,c,~]=(unique(A,'first'));
idx=(ismember((1:numel(A)),c));
A(~idx)=0
c is the index of unique values in A the left out indices contain duplicate values. The above method works for arbitrary vectors too not only for sorted vector.

Bruno Luong
Bruno Luong el 15 de Nov. de 2018
Editada: Bruno Luong el 15 de Nov. de 2018
For array with finite elements
A.*[1,diff(A)~=0]

Categorías

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

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by