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

6 次查看(过去 30 天)
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 个评论
Jan
Jan 2013-7-8
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.

请先登录,再进行评论。

采纳的回答

Evan
Evan 2013-7-8
编辑:Evan 2013-7-8
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')

更多回答(2 个)

Jan
Jan 2013-7-8
编辑:Jan 2013-7-8
"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 个评论
Evan
Evan 2013-7-8
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.

请先登录,再进行评论。


Azzi Abdelmalek
Azzi Abdelmalek 2013-7-8
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 个评论
Jan
Jan 2013-7-8
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Dates and Time 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by