Trying to compare datetimes in array to a separate predetermined datetime via function/for loop/if statement

12 visualizaciones (últimos 30 días)

Hi all,

I am trying to write a function that removes all rows of data after associated with a certain datetime. The idea was for a loop to go through each row of my datetime column and compare that datetime to 2024-07-06. If greater (after this date) the row gets deleted via my if statement. This is the code I wrote:

 function [output] = remove_after_07(file_name)
   new  = file_name ;
   for index = 1:length(file_name.date_only)
      if index > 2024-07-06
         index = []
      end 
   end
   output                   = new ;
end

This is the error I get:

 ‘Comparison is not defined between datetime and double arrays.’

How can I make it compare the actual dates listed in the column instead of the array?

Thank you!

Respuesta aceptada

dpb
dpb el 10 de Abr. de 2025
Editada: dpb el 11 de Abr. de 2025
What does file_name.date_only return an array of datenums or a date string? How to compare depends upon what you're trying to compare to.
In the expression
if index > 2024-07-06
the 2024-07-06 looks like an arithmetic expression and so the result of the line is equivalent to
if index > 2011
after subtracting a total of 13 from 2024.
The above code snippet doesn't look as though it could actually return that error, however, because in
for index = 1:length(file_name.date_only)
index will be a range of integers and so the comparison in the if would be two doubles compared to each other.
If file_name.date_only is actually an array of datenum, then
function [output] = remove_after_07(file_name)
% remove elements from input array after 2024-07-06
CULL_DATE=datetime('2024-07-06','InputFormat','yyyy-MM-dd'); % put data in variable so can change
ixBefore=(file_name.date_only<=CULL_DATE); % logical vector of those to KEEP
output=file_name(ixBefore,:); % return those
end
  3 comentarios
dpb
dpb el 11 de Abr. de 2025
Indeed, thanks, Walter. I forgot the variable filename isn't just an array as is the value. I made the correction plus added the missing closing parentheses that @Kristine caught in the Answer...

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Calendar en Help Center y File Exchange.

Productos


Versión

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by