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

7 次查看(过去 30 天)
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

采纳的回答

Bruno Luong
Bruno Luong 2018-10-12
编辑:Bruno Luong 2018-10-12
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

更多回答(1 个)

Sean de Wolski
Sean de Wolski 2018-10-12
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 个评论
Mekala balaji
Mekala balaji 2018-10-12
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).

请先登录,再进行评论。

Community Treasure Hunt

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

Start Hunting!

Translated by