Azzera filtri
Azzera filtri

Execute a for loop over a certain time period.

9 visualizzazioni (ultimi 30 giorni)
I use a function called uigetdate to get the date as a number (e.g. 736850). I then want to find the number of elapsed days for any given year, starting with jan 1. My code is as follows and I would rather put it in a loop than have to keep typing different years (the only thing that changes are the years). note: GMT_day1 equals something like 164. How do I make a loop for this?
day1 = uigetdate;
day1 = floor(day1);
day2 = uigetdate;
day2 = floor(day2);
if day1 > datenum(2016,12,31) && day2 < datenum(2017,12,31)
time1 = datenum(2016,12,31);
GMT_day1 = day1 - time1;
GMT_day2 = day2 - time1;
elseif day1 > datenum(2017,12,31) && day2 < datenum(2018,12,31)
time1 = datenum(2017,12,31);
GMT_day1 = day1 - time1;
GMT_day2 = day2 - time1;
  3 Commenti
JohnGalt
JohnGalt il 15 Giu 2017
I'm not sure what you're asking as you're only covering some of the possibilities.. you don't check if the years of day1 and day2 are the same just if one is after a date AND the other is before that date...
you can find the year of the date usind the 'datevec' function
tmp = datevec(day1);
year_day1 = tmp(1);
Guillaume
Guillaume il 15 Giu 2017
The name of your variables are extremely misleading. day1, day2, time1 are all dates (i.e. day+month+year+time).
I also do not understand the purpose of your ifs. What if day1 and day2 are not in the same year?

Accedi per commentare.

Risposta accettata

Guillaume
Guillaume il 15 Giu 2017
Modificato: Guillaume il 15 Giu 2017
Does anyone know how to make a loop that changes the year for a hundred iterations?
I'm really not sure what you're asking. Certainly, the question above is trivially solved:
for year = 2016:2016+100
%do something with year
end
edit: however, if all you want to do is calculate the number of days between a data and the start of the year then loops and ifs are absolutely not needed. Using modern datetime instead of the outdated datenum:
d = datetime(uigetdate(), 'ConvertFrom', 'datenum');
%set time to 00:00:00 (optional if just calculating number of days elapsed since start of year)
d = dateshift(d, 'start', 'day');
%calculate numbers of days since start of same year
elapseddays = days(d - dateshift(d, 'start', 'year'));

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by