I have a cell array of ('RUN_1';'RUN_10';'RUN_11';'RUN_12';'RUN_13';....;'RUN_19';'RUN_2';'RUN_20';'RUN_21';...;'RUN_99') How to arrange this in ascending order of the numbers like ('RUN_1';'RUN_2';'RUN_3';...;'RUN-99')

回答 (3 件)

Stephen23
Stephen23 2017 年 8 月 30 日
編集済み: Stephen23 2017 年 8 月 30 日

1 投票

Download my FEX submission natsort. Then simply:
natsort(C)
where C is your cell array.
KSSV
KSSV 2017 年 8 月 30 日

1 投票

str = {'RUN_1';'RUN_10';'RUN_13';'RUN_12';'RUN_11'} ;
val = zeros(length(str),1) ;
for i = 1:length(str)
val(i) = str2double(regexp(str{i},'-?\d+','match')) ;
end
[val1,idx] = sort(val,'ascend') ;
iwant = str(idx) ;

1 件のコメント

Stephen23
Stephen23 2017 年 8 月 30 日
Note that both regexp and str2double accept cell array inputs, so the loop is totally superfluous.

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

Jan
Jan 2017 年 8 月 30 日
編集済み: Jan 2017 年 8 月 30 日

1 投票

If this is time critical, try:
str = {'RUN_1';'RUN_10';'RUN_13';'RUN_12';'RUN_11'} ;
[~, order] = sort(sscanf(sprintf('%s*', str4{:}), 'RUN_%i*'));
str = str(order);
To my surprise this is even efficient for large inputs and the creation of the big intermediate string is still faster than e.g. a C-Mex with sscanf in a loop.

1 件のコメント

Stephen23
Stephen23 2017 年 8 月 30 日
Yes, the sprintf + sscanf combination is quite efficient. For some interesting timing measurements related to this see:

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

カテゴリ

ヘルプ センター および File Exchange で Characters and Strings についてさらに検索

質問済み:

2017 年 8 月 30 日

コメント済み:

2017 年 8 月 30 日

Community Treasure Hunt

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

Start Hunting!

Translated by