Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
Sort cell array of strings but their nums

Subject: Sort cell array of strings but their nums

From: CyberFrog

Date: 15 Jun, 2010 10:30:25

Message: 1 of 4

Hi all,

I have a cell array of strings:

str = {'13' '2' '3'}

ans =

    '13' '2' '3'

How can I simply sort this in ascending order? I know ther are really numbers but I am surprrised between the sort, sortrows and even cellfun commands I cannot get to sort this in ascedning order? Can someone ease my pain please

Tnaks

CF

Subject: Sort cell array of strings but their nums

From: dpb

Date: 15 Jun, 2010 12:52:15

Message: 2 of 4

CyberFrog wrote:
> Hi all,
>
> I have a cell array of strings:
>
> str = {'13' '2' '3'}
>
> ans =
> '13' '2' '3'
>
> How can I simply sort this in ascending order? I know ther are really
> numbers but I am surprrised between the sort, sortrows and even cellfun
> commands I cannot get to sort this in ascedning order? Can someone ease
> my pain please
...

Not sure...my version predates fully implemented cellfun so can't test
and therefore am not proficient w/ it but...

I think you need to nest str2double() to convert the strings to numeric
then apply sort() to its result

In my version the only way to get the strings to numeric is via for
loop...surely that's been improved but I don't know how, precisely other
than the above guess.

--

Subject: Sort cell array of strings but their nums

From: Sean

Date: 15 Jun, 2010 12:57:05

Message: 3 of 4

"CyberFrog" <domlee55@hotmail.com> wrote in message <hv7ko1$got$1@fred.mathworks.com>...
> Hi all,
>
> I have a cell array of strings:
>
> str = {'13' '2' '3'}
>
> ans =
>
> '13' '2' '3'
>
> How can I simply sort this in ascending order? I know ther are really numbers but I am surprrised between the sort, sortrows and even cellfun commands I cannot get to sort this in ascedning order? Can someone ease my pain please
>
> Tnaks
>
> CF

%%%
>> C = {'123' '32' '145' '96' '3.14159'}'
>> sortrows(C) %works for me
%%%

I think what's confusing you is that it is not sorting by complete number but by first number since they're strings. I.e.
'13'<'7' since the '1' is first and '1' is less than '7'
If you want 7<13 make it numeric.

Good Luck!

Subject: Sort cell array of strings but their nums

From: Myncroft

Date: 1 Aug, 2012 18:43:13

Message: 4 of 4

It took me a while to figure out, but this seems to work:
strtrim(cellstr(num2str(sort(str2double(C)))))

It's probably not as compact as it could be, though.

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us