how to sort array of time format from min to max time value?

3 views (last 30 days)
Hi all,
I have a 2-dimension array which its elements are time format, such as 22:13:98. I want to sort each row of this array in the ascending format, I mean from minimum time to maximum time. Any help is appreciated.
  1 Comment
Jan
Jan on 8 Jul 2013
To be exact: Most likely "22:13:98" is a string, which means a CHAR vector. Then the "elements" are characters. But perhaps you mean a {N x 1} cell string, and the element is really the string '22:13:98'. So please post the code, which creates a relevant part of your data, such that this important detail is clear.

Sign in to comment.

Accepted Answer

Evan
Evan on 8 Jul 2013
Edited: Evan on 8 Jul 2013
help sort
Example:
A = magic(5);
sort(A,2)
If you want to convert your time data to a numeric representation for sorting, try datenum.
help datenum
Example:
datenum('22:13:98','hh:mm:ss')

More Answers (2)

Jan
Jan on 8 Jul 2013
Edited: Jan on 8 Jul 2013
"22:13:98" is a strange example, because times wrap after 59 seconds usually.
I assume these times are stored in a matrix of type CHAR like this:
time = ['22:13:58'; ...
'22:14:15'; ...
'21:14:16'];
Then sortrows is sufficient already, because the alphabetical order equals the numerical time order also:
sorted = sortrows(time);
A conversion to the numerical time format would be required and useful only, if you really have mal-formatted times like "22:13:98" and want to compare it with "22:14:37".
  1 Comment
Evan
Evan on 8 Jul 2013
Ahhh, that's it. For some reason, I always mistakenly remember being able to pass in 'rows' as an argument to sort instead of the numerical arguments. I had forgotten there was an entirely separate function. This must be what I've been thinking of.

Sign in to comment.


Azzi Abdelmalek
Azzi Abdelmalek on 8 Jul 2013
A={'22:14:98' '22:13:98' '22:15:98';'22:17:98' '22:18:98' '22:11:98'}
out=arrayfun(@(x) datestr(x,'HH:MM:SS'),sort(cellfun(@datenum,A),2),'un',0)
  1 Comment
Jan
Jan on 8 Jul 2013
Actually I wanted to mention, that CELLFUN and ARRAYFUN can be omitted here, but this does not work at least in R2009a and 2011b:
A = {'22:14:98' '22:13:98' '22:15:98';'22:17:98' '22:18:98' '22:11:98'};
size(cellfun(@datenum, A)) % [2 x 3] as wanted
size(datenum(A)) % [3 x 1] doe!
But the ARRAYFUN can be omitted:
out = cellstr(datestr(sort(cellfun(@datenum,A),2), 'HH:MM:SS'));
out = reshape(out, size(A));
Anyhow, this isn't substantially nicer or faster. Unfortunately datestr does not reply a cellstring directly.

Sign in to comment.

Categories

Find more on Dates and Time in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!