Sorting a cell containing character vectors
1 次查看(过去 30 天)
显示 更早的评论
I'm trying to sort a cell of character vectors using the function
sort()
The input cell of character vectors are as follows:
A={ 3-aaa,
2-bbb,
1-abc,
10-acb,
21- cab}
sort(A)
The output is:
1-abc
10-acb
2-bbb
21- cab
3-aaa
How do I numerically sort it as
1-abc
2-bbb
3-aaa
10-acb
21- cab
0 个评论
采纳的回答
Andrei Bobrov
2017-7-10
A={ '3-aaa'
'2-bbb'
'1-abc'
'10-acb'
'21- cab'}
[~,ii] = sort(str2double(regexp(A,'\d+','match','once')));
out = A(ii)
0 个评论
更多回答(2 个)
Mark Fajet
2017-7-10
Since the problem is that you want to sort numerically, but the sort function sees these as character vectors, you're going to want to parse out the numbers from each cell containing character vectors. Using cellfun, it can be done. Obtaining the numbers from each cell can be done like so:
cellfun(@(B)str2num(B(1:find(B=='-')-1)),A,'un',0)
In the end, your code may look like this:
A={ '3-aaa',
'2-bbb',
'1-abc',
'10-acb',
'21- cab'}
num_cells = cellfun(@(B)str2num(B(1:find(B=='-')-1)),A,'un',0)
nums = cell2mat(num_cells)
[numsSorted, i] = sort(nums)
A(i)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!