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

7 ビュー (過去 30 日間)
Mekala balaji
Mekala balaji 2018 年 10 月 12 日
編集済み: Bruno Luong 2018 年 10 月 12 日
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