Sorting by multiple columns in a table with natural number sorting

7 ビュー (過去 30 日間)
Centauri Jolene
Centauri Jolene 2019 年 4 月 20 日
コメント済み: Cris LaPierre 2019 年 4 月 21 日
I have a table of data that I want to sort by pair number and by trial number.
The issue is that if I use:
data = sortrows(data, {'pairNum', 'trialNum'}, {'ascend', 'ascend'});
It sorts with trial 10 being before trial 1.
However, if I try and use Stephen Cobeldick's nat sort function, I can't take into account the pair number as well as the trial number so it ends up sorting with all trial 1s, then all trial 2s etc.. (doesnt preserve the order of the pairs).
Is there a way to sort my table so that my pairs go from 1-100, and within those pairs, the trial numbers go from 1-100?
Also, I tried adding zeros to the trial numbers so that it would hopefully sort 01 before 10, but when I convert to a number using str2num and/or str2double, it gets rid of the leading zeros.
data.trialNum = strsplit(sprintf('%02d ',data.trialNum))';
The datatset is attached as a .mat file.
  2 件のコメント
Andrei Bobrov
Andrei Bobrov 2019 年 4 月 20 日
Please attach small example your data as mat-file.
Centauri Jolene
Centauri Jolene 2019 年 4 月 20 日
Thanks, I've attached a sample.

サインインしてコメントする。

採用された回答

Cris LaPierre
Cris LaPierre 2019 年 4 月 20 日
編集済み: Cris LaPierre 2019 年 4 月 20 日
Here's a simple example that works for me:
pairNum = randi(15,1,200)';
trialNum = randi(15,1,200)';
data=table(pairNum, trialNum)
data = sortrows(data,{'pairNum','trialNum'})
  3 件のコメント
Centauri Jolene
Centauri Jolene 2019 年 4 月 21 日
Thanks. I ran my code line by line and you're right, it seems to be working. I must have been doing something wrong...
The trial numbers are orignially strings ('Trial1', 'Trial2', etc) so I convert the cell array of strings into a character array, and then extract the numbers at the end of each string and finally convert to numbers.
Cris LaPierre
Cris LaPierre 2019 年 4 月 21 日
There is also a categorical data type. That may work for your needs. Check it out.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

製品


リリース

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by