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]

 Respuesta aceptada

Andrew Newell
Andrew Newell el 6 de Abr. de 2011
[~,I] = sort(cellfun(@length,A));
A = A(I);

4 comentarios

Jan
Jan el 6 de Abr. de 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 el 6 de Abr. de 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 el 6 de Abr. de 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 el 6 de Abr. de 2011
You're right - the string call is about 20 times faster on my machine.

Iniciar sesión para comentar.

Más respuestas (1)

Mariam Osmann
Mariam Osmann el 7 de Abr. de 2011

0 votos

Thanks

Categorías

Productos

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by