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]

 Réponse acceptée

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

4 commentaires

Jan
Jan le 6 Avr 2011
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.
Andrew Newell
Andrew Newell le 6 Avr 2011
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 le 6 Avr 2011
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??
Andrew Newell
Andrew Newell le 6 Avr 2011
You're right - the string call is about 20 times faster on my machine.

Connectez-vous pour commenter.

Plus de réponses (1)

Mariam Osmann
Mariam Osmann le 7 Avr 2011

0 votes

Thanks

Catégories

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by