Sort cell array according to number of elements

A= [-0.054;-0.43;0.022] [-0.43;-0.18] [0.02;0.002;-0.202;-0.41]
Before applying cell2mat I want to reorder the array in ascending order according to the number of elements so NewA= [-0.43;-0.18] [-0.054;-0.43;0.022] [0.02;0.002;-0.202;-0.41]

 채택된 답변

Andrew Newell
Andrew Newell 2011년 4월 6일

2 개 추천

[~,I] = sort(cellfun(@length,A));
A = A(I);

댓글 수: 4

Jan
Jan 2011년 4월 6일
cellfun('length', A) is remarkably faster. cellfun(@length, A) uses mexCallMATLAB for each cell element, but the methods defined by a string are perfromend inside the Mex function.
That's strange. In the documentation for cellfun in MATLAB 2010b, the string input is described as being available for backward compatibility - implying that it's not the preferred choice.
Jan
Jan 2011년 4월 6일
Simply try it. Older Matlab version contained the C-source code of CELLFUN. It would be very helpful, if much more of these sweets is still available.
*But*: Perhaps a tricky prgorammer has found a method now to recognize @length such that no calls to external functions is necessary??
You're right - the string call is about 20 times faster on my machine.

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

추가 답변 (1개)

Mariam Osmann
Mariam Osmann 2011년 4월 7일

0 개 추천

Thanks

카테고리

도움말 센터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