Trying to compare datetimes in array to a separate predetermined datetime via function/for loop/if statement
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
dpb
2025-4-10
编辑:dpb
2025-4-11
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calendar 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!