Sorting a cell containing character vectors

1 Ansicht (letzte 30 Tage)
Anush Lingamoorthy
Anush Lingamoorthy am 10 Jul. 2017
Beantwortet: Andrei Bobrov am 10 Jul. 2017
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

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 10 Jul. 2017
A={ '3-aaa'
'2-bbb'
'1-abc'
'10-acb'
'21- cab'}
[~,ii] = sort(str2double(regexp(A,'\d+','match','once')));
out = A(ii)

Weitere Antworten (2)

Walter Roberson
Walter Roberson am 10 Jul. 2017
Look in the File Exchange for "natural sort"

Mark Fajet
Mark Fajet am 10 Jul. 2017
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)
After this, you'd want to do something similar to this example
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)

Kategorien

Mehr zu Graphics Object Programming finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by