calculate week of year

6 ビュー (過去 30 日間)
Richard
Richard 2012 年 12 月 18 日
コメント済み: Erik Johannes Loo 2021 年 10 月 25 日
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 methdo for finding week number?

採用された回答

Jan
Jan 2012 年 12 月 18 日
function weekOfYear = yourWeekNum(s)
% Get 1st of January of the year:
v = datevec(s);
v1 = v;
v1(:, 2:3) = 1;
v1(:, 4:6) = 0;
s1 = datenum(v1);
dayOfYear = s - s1;
weekOfYear = floor(dayOfYear / 7) + 1;
Please check this, because it is written in the editor and not tested.
  2 件のコメント
Richard
Richard 2012 年 12 月 18 日
works great.
DWag
DWag 2020 年 3 月 27 日
Yes it's great! And just a note for whoever uses it in the future, choose a date and double-check it to make sure it rounds to your needs. I rounded up isntead of having partial days.

サインインしてコメントする。

その他の回答 (1 件)

Steven Lord
Steven Lord 2020 年 3 月 27 日
Since the original question was written, we introduced datetime. If you're representing your time and date data as a datetime, call week on your datetime with 'weekofyear' as the weekType input.
  2 件のコメント
Rahul Shinde
Rahul Shinde 2021 年 7 月 22 日
I tried running the code
week(datetime(2016,2,29))
I am expecting Week 9 as per ISO-8601.(here)
However I am getting ans as 10 in my matlab command window.
Am I missing anything?
Regards,
Erik Johannes Loo
Erik Johannes Loo 2021 年 10 月 25 日
I will suggest something that I am not 100% sure it is correct - but I also haven't found satisfactory answers elsewhere:
sum(weekday(dateshift(inputDate, 'start', 'year'):dateshift(inputDate, 'end', 'week')) == 5)
This snippet basically counts the no. of Thursdays up to and including the week of the input date and should satisfy the ISO standard definition that the first week is (as per Wikipedia):
  • the week with the starting year's first Thursday in it (the formal ISO definition)

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeDates and Time についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by