在matlab中将小时转换为时间

Convert hours to time in matlab

如何将小时矢量(例如 22.93)转换为一天中的时间?

所以 22.93 应该转换为 22:55:48 下午?谢谢!

如果您正在做的事情允许您生成时间值,我建议您使用以下格式,因为所有函数都是内置的。

http://www.mathworks.com/help/matlab/ref/datenum.html

否则,如果您无法控制数据的呈现方式,您可能希望将向量转换为元胞数组,以便您可以在元胞数组上使用 cellfun(functionName,matrix) 来应用函数 "functionName"到每个单元格。然后你所要做的就是编写一个函数将小时转换为标准时间格式并用它替换 functionName。

% hours h minutes m seconds s
h0=22.93;

h=floor(h0)
m=floor( (h0-floor(h0))*60 ) 
s=60*( (h0-floor(h0))*60  -floor( (h0-floor(h0))*60 ) )

讨论here, this can be done using datestr

>> datestr(22.93/24,'HH:MM:SS')

ans =

22:55:48

请注意,我除以 24 因为 datestr 期望小数部分代表 "percentage of a day"(有 24 小时)。

一个向量的例子,也包括 AM/PM 后缀:

v = [22.93 13.6167 16.3334];
strcat(datestr(v(:)/24,'HH:MM:SS'),{' '},datestr(v(:)/24,'AM'))

ans = 

    '22:55:48 PM'
    '13:37:00 PM'
    '16:20:00 PM'

请注意,这里的结果是 char 行向量的 cell 数组,在第一种情况下它是 char 数组。