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

8 views (last 30 days)
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

Accepted Answer

Bruno Luong
Bruno Luong on 12 Oct 2018
Edited: Bruno Luong on 12 Oct 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

More Answers (1)

Sean de Wolski
Sean de Wolski on 12 Oct 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 Comment
Mekala balaji
Mekala balaji on 12 Oct 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).

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!