Trying to compare datetimes in array to a separate predetermined datetime via function/for loop/if statement
3 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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!
0 Commenti
Risposta accettata
dpb
il 10 Apr 2025
Modificato: dpb
il 11 Apr 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Calendar in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!