1

I would like to sort a cell array according to one of the columns. The array is created by textscan function. There are some answers on web, but I still cannot get it working. I have the following array:

>> DATA

DATA = 

    {303427x1 cell}    {303427x1 cell}    {303427x1 cell}    {303427x1 cell}    [303427x1 uint32]    [303427x1 double]    [303427x1 uint32]    [303427x1 int32]    {303427x1 cell}

Important is the sixth column, which are times converted by datenum function. I want to sort the whole DATA by this column but with the link to another columns. Normal sort or sortrows doesnt work for me. Could you help me please?

3
  • What was the original format of your date strings? Have you verified the datenum output is good? Commented Feb 6, 2012 at 23:21
  • format was YYYY-MM-DD HH:MM:SS, the output of datenum is correct, I checked it. Commented Feb 7, 2012 at 10:28
  • You can mark an answer "accepted" by clicking the check mark icon to the left of the answer text. Commented Feb 8, 2012 at 2:20

2 Answers 2

2

I take it you want to sort within each cell of DATA, correct? The datenum function produces serial time stamps since "year zero," so they can be sorted normally.

times = DATA{6};
[~,idx] = sort(times,'ascend');
for i=1:length(DATA)
    DATA{i} = DATA{i}(idx);
end
Sign up to request clarification or add additional context in comments.

Comments

1

You can avoid for-loop in @reve_etrange's answer by using CELLFUN after you get the sorting index idx.

DATA = cellfun(@(x) x(idx), DATA, 'UniformOutput', false);

5 Comments

Just a note, cellfun does let you fit the code on one line, but it simply wraps the loop and adds a little overhead (it doesn't parallelize in any way). Ultimately just a style choice.
@reve_etrange - check out stackoverflow.com/questions/8881735/…. cellfun can be much faster in some cases.
@Andrey - Only with a predefined list of functions, which can be passed to cellfun as strings. See the "backwards compatibility" section of the documentation.
@reve_etrange, thanks for the info! By the way, do you have any idea why the 'length' syntax faster than @length? (See the linked answer above).
both suggestion works for me, thanks to both of you. I cant compare what is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.