Very simple question about strings

2 次查看(过去 30 天)
Hello all
I have a cell containing stings something like this:
A={'SI1','SI12','SI13','SI2'};
I have to arrange these strings either in ascending order or in descending based on the numbers they are having. Can anyone please guide?
Regards
  1 个评论
Stephen23
Stephen23 2015-5-27
编辑:Stephen23 2015-5-27
You can simply use my FEX submission natsort, which performs a natural order sort on a cell array of strings:
>> A = {'SI1','SI12','SI13','SI2'};
>> natsort(A)
ans =
'SI1' 'SI2' 'SI12' 'SI13'

请先登录,再进行评论。

采纳的回答

David Young
David Young 2014-8-1
"According to the numbers" is ambiguous.
This sorts the strings in ascending order, making the digit in position 3 more significant than the digit in position 4, etc.:
Asorted = sort(A);
Your example is already sorted by this criterion.
This, on the other hand, makes the last digit the least significant, regardless of how many digits there are. It assumes that there are always 2 characters to ignore at the start:
nums = cellfun(@(s) str2double(s(3:end)), A);
[~, indexes] = sort(nums);
Asorted = A(indexes);

更多回答(1 个)

Honglei Chen
Honglei Chen 2014-8-1

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by