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
채택된 답변
추가 답변 (1개)
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
Jan
2011년 4월 4일
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
2011년 4월 4일
Wow, that's pretty slick! I wouldn't have thought of that.
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
카테고리
도움말 센터 및 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!