Sort a cell array of char

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

 采纳的回答

The question is not clear. This is a contradiction:
1. "cell array of chars" 2. "(some of the cells should be strings while other should be doubles)"
From the later text I guess, you want to sort a cell vector which contains scalar doubles:
C = {1001, 112, 14};
[dummy, index] = sort([C{:}]);
sortedC = C(index);
CELLFUN(@double, ...) converts each element of the cell to a DOUBLE - therefore it does no change anything here!
 
EDITED: Now a method to sort a cell string according to the numbers the strings represent:
C = {'1001', '112', '14'};
Str = sprintf('%s,', C{:});
D = sscanf(Str, '%g,');
[dummy, index] = sort(D);
sortedC = C(index);

3 个评论

I wasn't clear.
I have a cell array (5000 X 150 cell). Each cell is a char. Whether I have strings or numbers in this cell array they are defined as chars.
As I want to sort only the rows in which I have numbers I tried to convert those to doubles.
Is this explanation better?
Does the above added sorting method help?
Yes! Thank you! I would never think of doing something like this.
There is no direct way to sort such cell array?
Anyway, thank you very much.

请先登录,再进行评论。

更多回答(1 个)

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 个评论

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
Wow, that's pretty slick! I wouldn't have thought of that.
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

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Shifting and Sorting Matrices 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by