Calculate week numbers in matlab - matlab

I have an annual time series where measurements are recorded at hourly intervals:
StartDate = '2011-01-01 00:00';
EndDate = '2011-12-031 23:00';
DateTime=datevec(datenum(StartDate,'yyyy-mm-dd HH:MM'):60/(60*24):...
datenum(EndDate,'yyyy-mm-dd HH:MM'));
dat = 2+(20-2).*rand(size(DateTime,1),1);
I would like to calculate the mean 24 hour cycle for each week of the year i.e. for week 1, day of year 1 to 7 I want to calculate the average 00:00, 01:00,... and so on so eventually I will end up with 52, 24 hour series i.e. one for each week of the year. Matlab does have a function called 'weeknum' which returns the week number from a given seriel date number, however, this function is in the financial toolbox. Can anyone suggest an alternative method for finding week number?

Maybe this can be of help (I'm using the current date and time as an example):
c = datevec(datestr(now));
week_num = ceil(diff(datenum([c(1), 1, 1, 0, 0, 0; c])) / 7)
I'm not sure how this solution handles edge cases properly, but I think it's a good place to start.
You can also verify it with this website that tells the current week number.
Applying this to your example can be done, for example, like so:
weeknum = #(v)ceil(diff(datenum([v(1), 1, 1, 0, 0, 0; v(:)'])) / 7);
arrayfun(#(n)weeknum(DateTime(n, :)), 1:size(DateTime, 1))'

According to Wikipedia, ISO week number is calculated like this.
I did it for today as an example.
offsetNotLeap = [0 31 59 90 120 151 181 212 243 273 304 334];
offsetLeap = [0 31 60 91 121 152 182 213 244 274 305 335];
todayVector = datevec(today);
todayNum = today;
ordinalDay = offsetLeap(todayVector(2)) + todayVector(3);
dayOfTheWeek = weekday(todayNum);
weekNumber = fix((ordinalDay - dayOfTheWeek + 10)/ 7)
weekNumber =
51
I didn't do the checks for 0 and 53 cases.
Also note that MATLAB's weekday function gives Sunday's index as 1, so if you want to make Monday's index 1, you need to do some adjustments. ISO says that Monday should be 1.

Just a simple weekday function with Monday as the first day of the week:
function [ daynumber,dayname ] = weekd( date )
%WEEKD Returns the day number and day name based on the input date
% First day of week
% -----------------
% The first day of the week is Monday.
%
% Parameter
% ---------
% date = Input date -> format: dd.mm.yyyy / Example: 21.11.2015
[dn,dayname] = weekday(datenum(date,'dd.mm.yyyy'));
if dn == 1;
daynumber = 7;
elseif dn >= 2 && dn <= 7
daynumber = dn - 1;
else
error('Invalid weekday number.'),
end
end

although some time has past since you posted your question, I want to give an additional answer, if people will have the same issue as me. As HebeleHododo already indicated, there exists a rule posted on Wikipedia how to compute the ISO week number. But anyhow, I wasn't able to find a generic code snippet for it.
Therefore, I developed the following generic method which is able to take vectors, matrices or single values of arbitrary datetimes with arbitrary reference years. Appreciate to read any constructive feedback. I successfully ran it on MATLAB R2017a and tested it further for some edge cases.
function week_num = get_week_num(dtimes)
dnums = datenum(dtimes);
firsts = datenum(year(dtimes), 1, 1);
ordinal = floor(dnums - firsts);
wday = weekday(dtimes) - 1;
wday(wday == 0) = 7;
week_num = floor((ordinal + wday + 10) / 7);
end

Related

How can I convert time from seconds to decimal year in Matlab?

I have a dataset which includes the seconds that have passed since 2000-01-01 00:00:00.0 and I would like them to be converted to decimal years (for example 2013.87).
An example from the dataset:
416554767.293262
416554768.037637
416554768.782013
416554769.526386
416554770.270761
416554771.015136
416554771.759509
416554772.503884
416554773.248258
416554773.992632
416554774.737007
416554775.481381
416554776.225757
416554776.970131
416554777.714504
416554778.458880
Can anyone help me out on this?
Thanks!
You should be able to perform these computations using methods of datetime and duration. A bit like this. I've tried to be careful regarding the number of seconds / year, since of course that varies depending on whether the year in question is a leap year.
% Original data
data = [416554767.293262
416554768.037637
416554768.782013
416554769.526386
416554770.270761
416554771.015136
416554771.759509
416554772.503884
416554773.248258
416554773.992632
416554774.737007
416554775.481381
416554776.225757
416554776.970131
416554777.714504
416554778.458880];
% Original data is seconds since 'base':
base = datetime(2000,1,1);
% Get datetimes corresponding to 'data'
dates = base + seconds(data);
% Extract the year portion from the dates
wholeYears = year(dates);
% Extract the remainder of the dates as seconds
remainderInSeconds = seconds(dates - datetime(wholeYears,1,1));
% Calculate the number of seconds in each of the years
secondsPerYear = seconds(datetime(wholeYears + 1, 1, 1) - datetime(wholeYears, 1, 1));
% Final result is whole years + remainder expressed as years
result = wholeYears + (remainderInSeconds ./ secondsPerYear);
fprintf('%.16f\n', result);

Convert milliseconds into hours and plot

I'm trying to convert an array of milliseconds and its respective data. However I want to do so in hours and minutes.
Millis = [60000 120000 180000 240000....]
Power = [ 12 14 12 13 14 ...]
I've set it up so the data records every minute, hence the 60000 millis (= 1 minimte). I am trying to plot time on the x axis and power on the y. I would like to have the x axis displayed in hours and minutes with each respective power data corresponding to its respective time.
I've tried this
for i=2:length(Millis)
Conv2Min(i) = Millis(i) / 60000;
Time(i) = startTime + Conv2Min(i);
if (Time(i-1) > Time(i) + 60)
Time(i) + 100;
end
end
s = num2str(Time);
This in attempt to turn the milliseconds into hours starting at 08:00 and once 60 minutes have past going to 09:00, the problem is plotting this. I get a gap between 08:59 and 09:00. I also cannot maintain the 0=initial 0.
In this scenario it is preferable to work with datenum values and then use datetick to set the format of the tick labels of your plot to 'HH:MM'.
Let's suppose that you started taking measurements at t_1 = [HH_1, MM_1] and stopped taking measurements at t_2 = [HH_2, MM_2].
A cool trick to generate the array of datenum values is to use the following expression:
time_datenums = HH_1/24 + MM_1/1440 : 1/1440 : HH_2/24 + MM_2/1440;
Explanation:
We are creating a regularly-spaced vector time_datenums = A:B:C using the colon (:) operator, where A is the starting datenum value, B is the increment between datenum values and C is the ending datenum value.
Since your measurements have been taken every minute (60000 milliseconds), then the increment between datenum values should be of 1 minute too. As a day has 24 hours, that makes 1440 minutes a day, so use B = 1/1440 as the increment between vector elements, to get 1 minute increments.
For A and C we simply need to divide the hour digits by 24 and the minute digits by 1440 and sum them up like this:
A = HH_1/24 + MM_1/1440
C = HH_2/24 + MM_2/1440
So for example, if t_1 = [08, 00], then A = 08/24 + 00/1440. As simple as that.
Notice that this procedure doesn't use the datenum function at all, and still, it manages to generate a valid array of datenum values only taking into consideration the time of the datenum, without needing to bother about the date of the datenum. You can learn more about this here and here.
Going back to your original problem, let's have a look at the code:
time_millisec = 0:60000:9e6; % Time array in milliseconds.
power = 10*rand(size(time_millisec)); % Random power data.
% Elapsed time in milliseconds.
elapsed_millisec = time_millisec(end) - time_millisec(1);
% Integer part of elapsed hours.
elapsed_hours_int = fix(elapsed_millisec/(1000*60*60));
% Fractional part of elapsed hours.
elapsed_hours_frac = (elapsed_millisec/(1000*60*60)) - elapsed_hours_int;
t_1 = [08, 00]; % Start time 08:00
t_2 = [t_1(1) + elapsed_hours_int, t_1(2) + elapsed_hours_frac*60]; % Compute End time.
HH_1 = t_1(1); % Hour digits of t_1
MM_1 = t_1(2); % Minute digits of t_1
HH_2 = t_2(1); % Hour digits of t_2
MM_2 = t_2(2); % Minute digits of t_2
time_datenums = HH_1/24+MM_1/1440:1/1440:HH_2/24+MM_2/1440; % Array of datenums.
plot(time_datenums, power); % Plot data.
datetick('x', 'HH:MM'); % Set 'HH:MM' datetick format for the x axis.
This is the output:
I would use datenums:
Millis = [60000 120000 180000 240000 360000];
Power = [ 12 14 12 13 14 ];
d = [2017 05 01 08 00 00]; %starting point (y,m,d,h,m,s)
d = repmat(d,[length(Millis),1]);
d(:,6)=Millis/1000; %add them as seconds
D=datenum(d); %convert to datenums
plot(D,Power) %plot
datetick('x','HH:MM') %set the x-axis to datenums with HH:MM as format
an even shorter approach would be: (thanks to codeaviator for the idea)
Millis = [60000 120000 180000 240000 360000];
Power = [ 12 14 12 13 14 ];
D = 8/24+Millis/86400000; %24h / day, 86400000ms / day
plot(D,Power) %plot
datetick('x','HH:MM') %set the x-axis to datenums with HH:MM as format
I guess, there is an easier way using datetick and datenum, but I couldn't figure it out. This should solve your problem for now:
Millis=6e4:6e4:6e6;
power=randi([5 15],1,numel(Millis));
hours=floor(Millis/(6e4*60))+8; minutes=mod(Millis,(6e4*60))/6e4; % Calculate the hours and minutes of your Millisecond vector.
plot(Millis,power)
xlabels=arrayfun(#(x,y) sprintf('%d:%d',x,y),hours,minutes,'UniformOutput',0); % Create time-strings of the format HH:MM for your XTickLabels
tickDist=10; % define how often you want your XTicks (e.g. 1 if you want the ticks every minute)
set(gca,'XTick',Millis(tickDist:tickDist:end),'XTickLabel',xlabels(tickDist:tickDist:end))

Count days in MATLAB

I need to count X days starting on some specific day, but I don't know how to sum these days accosrding to the number of days on each month (e.g. February having 28 or 29, March 31 but April 30...).
I know there is the function daysact( startDate, endDate ), but this way I have to try dates until I reach the result I want, and what I need is for the program to count X days from the startDate and return the endDate. For example, if I want to count 90 days from tomorrow, I have done:
startDate = '8-jan-2016';
endDate = '7-apr-2016';
numDays = daysact( startDate, endDate );
but I have had to try dates until the function returned exactly 90 (I know it's fairly simple, but the final program will have to do this for different values of days and different starting dates...)
2014b and later:
datetime(2016,1,8) + days(90)
datetime(2016,1,8) + 90
datetime('today') + days(90)
datetime('today') + 90
datetime('tomorrow') + days(90)
datetime('tomorrow') + 90
startDate = '8-jan-2016';
NumDays = 90;
tmp = datevec(startDate);
tmp(3)=tmp(3)+90;
endDate = datestr(tmp)
This uses datevec to transform your string into a vector of [Y M D HH MM SS], so by adding the desired number of days, 90, to the third element you add 90 days to the start date. Then transform the vector back using datestr, which makes it a recognisable date again.
As per #excaza's comment datenum does approximately the same thing, returning the number of days since 0 January 0000, so the same could be accomplished using:
startDate = '8-jan-2016';
NumDays = 90;
endDate = datestr(datenum(startDate)+NumDays);
which is a bit more concise, at the cost of having to convert everything to fractions of days.
One-lining it because why not:
endDate = datestr(datenum('8-jan-2016')+90);
I wanted to post this as an alternative. It was mentioned by #excaza in a comment to #Adriaan's answer.
myDate = datenum(2016,1,8); % datenumber for january 8 2016
newDate = myDate + 90; % add 90 days
newDate2 = myDate + 2/24; % add 2 hours
newDate3 = myDate + 93/1440; % add 93 minutes
Then you can print the dates with datestr.
datestr(newDate)
ans =
07-Apr-2016
>> datestr(newDate2)
ans =
08-Jan-2016 02:00:00
>> datestr(newDate3)
ans =
08-Jan-2016 01:33:00
datenum can take many inputs and even user defined formats to read the date strings.

How to construct moving time average with different weights for different months?

So I want to construct a moving time average with different weights for different months. E.g. see the filter function at http://www.mathworks.com/help/matlab/data_analysis/filtering-data.html, where b = # of days in each month and a = # of days in a year.
The issue is, though, that the time-series is a series of temperatures for every month (and I want to construct a yearly average temperature for each set of possible years, where a year could be from March to February, for example). Using this approach, the first month in each window would be weighted as 31/365, irrespective of whether the first month is January or June.
In that case, the standard filter algorithm wouldn't work. Is there an alternative?
A solution that incorporates leap years would also be nice, but is not necessary for an initial solution.
A weighted average is defined as sum(x .* weights) / sum(weights). If you want to calculate this in a moving average kind of way, I guess you could do (untested):
moving_sum = #(n, x) filter(ones(1,n), 1, x);
moving_weighted_avg = moving_sum(12, temperature .* days_per_month) ...
./ moving_sum(12, days_per_month);
If temperature is a vector of monthly temperatures and days_per_month contains the actual number of days of the corresponding months, this should even work in case of leap years.
Edit to answer comment
You can reconstruct days_per_month like so:
start_year = 2003;
start_month = 10;
nmonth = 130;
month_offset = 0:nmonth - 1;
month = mod(start_month + month_offset - 1, 12) + 1;
year = start_year + floor((start_month + month_offset - 1) / 12);
days_in_month = eomday(year, month);
disp([month_offset; year; month; days_in_month]') %print table to check

Get year from day number counter

I have an integer that shows the number of days since Jan 1, 1970, where for instance 1969-12-31=-1, 1970-01-01=0, 1970-01-02=1, and so on. I would like to know an algorithm that will take this day number and tell me in which year the day is. So for instance days 0 to 364 lie in year 1970, days 365 to 729 lie in year 1971, and so on. Keep in mind that the algorithm must accept both positive and negative numbers; however, it does not need to deal with the Julian to Gregorian calendar changeover (i.e. we can assume that the current Gregorian calendar system stretches backward continuously in time).
I found the answer to my question. Here is some Java code that works.
public int yearFromDays(int days) {
double d0 = days + 719162;
double n400 = Math.floor(d0/146097.0);
double d1 = d0 % 146097;
double n100 = Math.floor(d1/36524.0);
double d2 = d1 % 36524;
double n4 = Math.floor(d2/1461.0);
double d3 = d2 % 1461;
double n1 = Math.floor(d3/365.0);
double year = 400*n400 + 100*n100 + 4*n4 + n1;
if (n100 != 4 && n1 != 4) year++;
return (int)year;
}
Here is a way to do it with the Java API:
public int yearFromDays(int days) {
Calendar c = Calendar.getInstance();
c.setTime(new Date(0));
c.add(Calendar.DATE, days);
return c.get(Calendar.YEAR);
}