如何正确生成带有5分钟时间戳的文件名



我使用下面的代码根据时间步长每隔五分钟生成一次文件名。但它工作不正常。如果你打开precipFileNames,你会看到中途,代码每5分钟停止一次,而是每1秒执行5分钟,这会生成这样的文件名:

E:MRMS2004PRECIPRATE.20040402.051959.tif

我该如何正确地执行此操作?

timeSteps = 417;
pathstr = 'E:MRMS2004';
startTime = 7.320395312500000e+05;
peakTime2 = 7.320400104166666e+05;
precipFileNames=cell(timeSteps,1);
for l = 1:timeSteps
%precipFileNames{m} = strcat(fileparts(refFile), filesep, datestr(startTime, 'yyyy'), filesep,'PRECIPRATE.',datestr(startTime, 'yyyymmdd.hhMMss'), '.tif');
precipFileNames{l} = strcat(pathstr(1:end-4), datestr(startTime, 'yyyy'), filesep, 'PRECIPRATE.',datestr(peakTime2, 'yyyymmdd.hhMMss'), '.tif');
peakTime2 = addtodate(peakTime2, -5, 'minute');  %No. of times we go back in time from peak time
end

日期/时间使用浮点数进行内部存储。每次循环时,都要将一个非常小的值(5分钟,0.0035)添加到一个相对较大的值(7e05-ish)中,这会导致浮点运算错误的累积。这些错误表现为与预期值的细微差异。

因为您在循环中一遍又一遍地执行此加法(到peakTime2),所以一次迭代的浮点误差会被放大,因为下一次迭代取决于上一次的结果。

与其不断更新peakTime2,我会更改delta值,并在循环中每次将其应用于原始日期时间对象。这样就不会累积错误,只需执行一次减法即可获得特定值。

for k = 1:timeSteps
% Compute how many minutes to shift this iteration
shift = -5 * (k - 1);
% Apply the shift to the reference time
thistime = addtodate(peakTime2, shift, 'minute');
% Create the filename
precipFileNames{k} = strcat(pathstr(1:end-4), ...
datestr(startTime, 'yyyy'), ...
filesep, ...
'PRECIPRATE.', ...
datestr(thistime, 'yyyymmdd.hhMMss'), ...
'.tif');
end

顺便说一句,为了让人们阅读您的代码,我强烈反对使用l作为变量,因为它看起来很像1

最新更新