gabboshow
gabboshow

Reputation: 5579

sort string according to first characters matlab

I have an cell array composed by several strings

names = {'2name_19surn', '3name_2surn', '1name_2surn', '10name_1surn'}

and I would like to sort them according to the prefixnumber.

I tried

[~,index] = sortrows(names.'); 
sorted_names = names(index); 

but I get

sorted_names = {'10name_1surn', '1name_2surn', '2name_19surn', '3name_2surn'}

instead of the desired

sorted_names = {'1name_2surn', '2name_19surn', '3name_2surn','10name_1surn'}

any suggestion?

Upvotes: 1

Views: 459

Answers (4)

Luis Mendo
Luis Mendo

Reputation: 112759

Simple approach using regular expressions:

r = regexp(names,'^\d+','match'); %// get prefixes
[~, ind] = sort(cellfun(@(c) str2num(c{1}), r)); %// convert to numbers and sort
sorted_names = names(ind); %// use index to build result

Upvotes: 2

Daniel1000
Daniel1000

Reputation: 797

You can deal with arbitrary patterns using a regular expression:

names = {'2name', '3name', '1name', '10name'}

match = regexpi(names,'(?<number>\d+)\D+','names'); % created with regex editor on rubular.com
match = cell2mat(match); % cell array to struct array
clear numbersStr
[numbersStr{1:length(match)}] = match.number; % cell array with number strings 
numbers = str2double(numbersStr); % vector of numbers
[B,I] = sort(numbers); % sorted vector of numbers (B) and the indices (I) 
clear namesSorted
[namesSorted{1:length(names)}] = names{I} % cell array with sorted name strings

Upvotes: 1

zinjaai
zinjaai

Reputation: 2385

As long as speed is not a concern you can loop through all strings and save the first digets in an array. Subsequently sort the array as usual...

names = {'2name_2', '3name', '1name', '10name'}
number_in_string = zeros(1,length(names));

% Read numbers from the strings
for ii = 1:length(names)
    number_in_string(ii) = sscanf(names{ii}, '%i');
end

% Sort names using number_in_string
[sorted, idx] = sort(number_in_string)
sorted_names = names(idx)

Upvotes: 2

lakshmen
lakshmen

Reputation: 29094

Take the file sort_nat from here

Then

names = {'2name', '3name', '1name', '10name'}
sort_nat(names)

returns

sorted_names = {'1name', '2name', '3name','10name'}

Upvotes: 1

Related Questions