Sort a cell array of char
Afficher commentaires plus anciens
Hi,
I have a cell array of chars (some of the cells should be strings while other should be doubles). Now I am trying to sort several of the rows that should be doubles and I get, of course, a sort from the left of the number as : 1001, 112, 14.. Tried to convert to double with both writing sort(double(...)) and cellfun(@double, ...,'Uniformoutput', false) and it won't accept: 1) ??? Error using ==> double Conversion to double from cell is not possible." 2)??? Error using ==> sort Input argument must be a cell array of strings. What can I do to get 14, 112, 1001... Thank you Keren
Réponse acceptée
Plus de réponses (1)
Teja Muppirala
le 4 Avr 2011
Instead of just "double" you should use "str2double". I'm pretty sure that does what you want.
A = {'1001', '112', '14'}
B = str2double(A)
[Bsorted,ordering] = sort(B)
3 commentaires
Jan
le 4 Avr 2011
Correct, but the SSCANF(SPRINTF('%g,', C{:}), '%g,') approach is much faster than STR2DOUBLE for a {1 x 5000} cell (Matlab 2009a):
C = cell(1, 5000);
for i=1:5000; C{i}=sprintf('%.0f', rand*1000); end
tic; d = str2double(C); toc % 0.20 sec
tic; e = sscanf(sprintf('%g,', C{:}), '%g,'); toc % 0.01 sec
Teja Muppirala
le 4 Avr 2011
Wow, that's pretty slick! I wouldn't have thought of that.
Jan
le 4 Avr 2011
And SPRINTF still wastes time, because it does not pre-allocate the output. Therefore using http://www.mathworks.com/matlabcentral/fileexchange/26077-cstr2string will make it twice as fast:
tic; e = sscanf(CStr2String(C, ','), '%g,'); toc % 0.005 sec
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!