What do I have to do to sort strings properly in Listbox?

3 views (last 30 days)
While I try to figure this out, I have problems again..
To sort strings in listbox,
e.g.,I have strings below! 'p1' 'p2' 'p10' 'p12' 'p21'
To sort those strings, I tried to use sort(),
and then, result was like this..
'p1' 'p10' 'p12' 'p2' 'p21'
%%%% :-( %%%%
But, I want to sort A as, 'p1' 'p2' 'p10' 'p12' 'p21'
What do I have to do for this?
I'm looking forward to your answer!
Geoff on 25 Jun 2012
Oh... probably... Meh, well, I'll stop being a grump and hack it out quickly again.
Haksun Lee
Haksun Lee on 25 Jun 2012
There was some misunderstanding..
Have a nice day everyone..
But I have to figure this out T.T
- Newbie programmer, H.S Lee

Sign in to comment.

Accepted Answer

Geoff on 25 Jun 2012
Don't ask the same question just because nobody answered it yesterday. If you are impatient, write a comment on it to bump it back up. People occasionally check through old questions to see what hasn't been answered. That's also a reason to accept answers - so people who do look back on old questions know not to check those that are already accepted.
Now... code, with no explanation this time.
A = {'p1', 'p10', 'p12', 'p2', 'p21'};
N = cellfun( @str2double, regexp(A, '\d+', 'match') )
[~,I] = sort(N);
B = A(I);
Stephen23 on 20 Feb 2016
Edited: Stephen23 on 21 Feb 2016
@Soroush Asarzadeh: This is trivial using my FEX submission natsort:
>> A = {'p10=34', 'p4=10', 'p2=11', 'p3=90', 'p21=55'};
>> natsort(A)
ans =
'p2=11' 'p3=90' 'p4=10' 'p10=34' 'p21=55'
Soroush Asarzadeh
Soroush Asarzadeh on 20 Feb 2016
@Walter thanks, it works now! @Stephan thank u for your answer

Sign in to comment.

More Answers (0)


Find more on Characters and Strings in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!