The Math Forum

Search All of the Math Forum:

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

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

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

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: 18,038
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" <> wrote in message
> "james bejon" wrote in message <k7u685$k6m$>...
>> "Nasser M. Abbasi" <> wrote in message
>> <k7u5ab$650$>...


> 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]

© The Math Forum at NCTM 1994-2018. All Rights Reserved.