How get row index of first and last appearance each unique cell element

8 visualizaciones (últimos 30 días)
Hi,
I have below cell array, and I want to get the unique elements based on 2nd column.
MUY09KT00 TW00.00
MUY09KT00 TW00.00
MUY09KT00 TW00.00
MHJ09KT00 PW00.00
MHJ09KT00 PW00.00
LHJ09KT00 NPW00.00
LHJ09KT00 NPW00.00
LHJ09KT00 NPW00.00
in this case, the unique element first index are:
1
4
6
in this case, the unique element last index are:
3
5
8

Respuesta aceptada

Bruno Luong
Bruno Luong el 12 de Oct. de 2018
Editada: Bruno Luong el 12 de Oct. de 2018
Make the output in the "stable" order:
x = ["MUY09KT00" "TW00.00"
"MUY09KT00" "TW00.00"
"MUY09KT00" "TW00.00"
"MHJ09KT00" "PW00.00"
"MHJ09KT00" "PW00.00"
"LHJ09KT00" "NPW00.00"
"LHJ09KT00" "NPW00.00"
"LHJ09KT00" "NPW00.00"]
[~,~,J] = unique(x(:,2)); % Based on the 2nd column
jump = find([true; diff(J); true]);
first = jump(1:end-1)
last = jump(2:end)-1
first =
1
4
6
last =
3
5
8

Más respuestas (1)

Sean de Wolski
Sean de Wolski el 12 de Oct. de 2018
Unique is your friend:
x = ["MUY09KT00" "TW00.00"
"MUY09KT00" "TW00.00"
"MUY09KT00" "TW00.00"
"MHJ09KT00" "PW00.00"
"MHJ09KT00" "PW00.00"
"LHJ09KT00" "NPW00.00"
"LHJ09KT00" "NPW00.00"
"LHJ09KT00" "NPW00.00"]
[~,first] = unique(x(:,1), 'first')
[~,last] = unique(x(:,1), 'last')
  1 comentario
Mekala balaji
Mekala balaji el 12 de Oct. de 2018
It works, but the index are in reverse order:
results are:
first:
6
4
1
last:
8
5
3
I thought of using flipud or sort to retain the order, is there any other way? I can not use stable (because we used first and last).

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by