Drexel dragonThe Math ForumDonate to the Math Forum

Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.

Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: sorting arrays in a cell array
Replies: 23   Last Post: Nov 15, 2012 11:16 AM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Steven Lord

Posts: 17,945
Registered: 12/7/04
Re: sorting arrays in a cell array
Posted: Nov 14, 2012 10:04 AM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

"Bruce Elliott" <bruce.elliott@jhuapl.nospam.edu> wrote in message
> "james bejon" wrote in message <k7u685$k6m$1@newscl01ah.mathworks.com>...
>> "Nasser M. Abbasi" <nma@12000.org> wrote in message
>> <k7u5ab$650$1@speranza.aioe.org>...


> Thanks for the responses. I'm not as adept as I should be with cellfun or
> arrayfun, so I had not considered this kind of approach.

Another CELLFUN approach:

firstElementsOfEachCell = cellfun(@(x) x(1), myCellArray); % This will error
if any of the cells are empty
[~, indices] = sort(firstElementsOfEachCell);

and now use indices to reorder the cell array as per the previous

> As it happens, my array are not likely to be large, no more than ten or
> twenty cells containing numeric arrays, most of which will be 2-by-1, but
> some might be 2-by-n, where n<10. My main concern is therefore not so much
> performance as it is complexity of code and easy maintainability by other
> users who might have less expertise with Matlab programming.
> In other words, I'm thinking the for-loop might not be such a bad
> trade-off, if I can't do the one-line version.

For such a small problem, if you preallocate firstElementsOfEachCell, using
the FOR loop to extract the first elements of each cell would probably be
more efficient (CELLFUN being a much bigger hammer than you need) and easier
to read.

Steve Lord
To contact Technical Support use the Contact Us link on

Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2015. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.