我目前正在开发一个关于在MATLAB上处理时差的小项目。我有两个输入文件; Time_in and Time_out
。这两个文件包含格式为2315 (GMT - Hours and Minute)
我在MATLAB上读过两个Time_in' and 'Time_out
,但我不知道如何进行减法。另外,我希望相应的答案仅在分钟域内(例如2小时30分钟= 150分钟)
答案 0 :(得分:3)
这是几种可能的解决方案之一:
首先,您应该将时间字符串转换为MATLAB序列号。如果您已完成此操作,则可以根据需要进行计算:
% input time as string
time_in = '2115';
time_out = '2345';
% read the input time as datenum
dTime_in = datenum(time_in,'HHMM');
dTime_out = datenum(time_out,'HHMM');
% subtract to get the time difference
timeDiff = abs(dTime_out - dTime_in);
% Get the minutes of the time difference
timeout = timeDiff * 24 * 60;
此外,要正确计算时差,您还应该在时间向量中放置一些有关日期的信息,以便计算午夜时分的正确时间。
如果您需要有关函数datenum
的更多信息,请阅读以下MATLAB文档部分:
https://de.mathworks.com/help/matlab/ref/datenum.html
有问题吗?
答案 1 :(得分:0)
在最近的MATLAB版本中,您可以将textscan
与datetime
和duration
数据类型结合使用来执行此操作。
% read the first file
fh1 = fopen('Time_in');
d1 = textscan(fh1, '%{HHmm}D');
fclose(fh1);
fh2 = fopen('Time_out');
d2 = textscan(fh2, '%{HHmm}D');
fclose(fh2);
注意格式说明符'%{HHmm}D'
告诉MATLAB将4位数字符串读入datetime
数组。
d1
和d2
现在是cell
个数组,其中唯一的元素是datetime
向量。您可以减去这些,然后使用minutes
函数查找分钟数。
result = minutes(d2{1} - d1{1})