0

I use the code below to generate filenames every five minutes based on the number of timesteps. But it's not working correctly. If you open precipFileNames, you will see that midway, the code stops doing it every 5 minutes and instead does 5 minutes 1 second which generates a filename like this:

E:\MRMS\2004\PRECIPRATE.20040402.051959.tif

How can I do this correctly?

timeSteps = 417;
pathstr = 'E:\MRMS\2004';
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
maximusdooku
  • 5,242
  • 10
  • 54
  • 94

1 Answers1

3

Date/times are internally stored using floating point numbers. Each time through the loop, you are adding a very small value (5 minutes, 0.0035) to a relatively large value (7e05-ish) and this causes an accumulation of floating point arithmetic errors. These errors manifest themselves as slight differences from your expected values.

Because you are performing this addition (to peakTime2) over and over again in a loop, the floating point error for one iteration is amplified as the next iteration depends upon the result of the previous one.

Rather than continuously updating peakTime2 I would alter the delta value and apply it to the original datetime object each time through the loop. This way there is no accumulation of error and you only perform one subtraction to get a particular value.

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

As a side-note, for the sake of people reading your code I would highly discourage using l as a variable as it looks a lot like 1.

Community
  • 1
  • 1
Suever
  • 64,497
  • 14
  • 82
  • 101