Sort a cell array of char

조회 수: 49 (최근 30일)
New
New 2011년 4월 4일
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

채택된 답변

Jan
Jan 2011년 4월 4일
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
Jan
Jan 2011년 4월 4일
Does the above added sorting method help?
New
New 2011년 4월 4일
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개)

Teja Muppirala
Teja Muppirala 2011년 4월 4일
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
Teja Muppirala
Teja Muppirala 2011년 4월 4일
Wow, that's pretty slick! I wouldn't have thought of that.
Jan
Jan 2011년 4월 4일
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

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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