How to use if/then to assign a year to a set of dates?
3 ビュー (過去 30 日間)
古いコメントを表示
I would like to add a new vector called "school_year" that assigns a year to each point. In this case, a school year will be considered as starting August 1 and ending the following year in July 31st. For example, August 1st, 2000 - July 31st, 2001 should be assigned as school year 2001.
I want to use an if/then based on the month/year to generate the "school_year" value for each data point. A hint I have been given in this assignment is to use an if/then statement, for example, if it is after July, then what?
So in this table, there would be a new column called school_year that should read the following:
2001
2001
2001
2001
2002
2002
2002
2002
2002
table_a = readtable('Data1.xlsx')
0 件のコメント
採用された回答
Les Beckham
2023 年 2 月 6 日
編集済み: Les Beckham
2023 年 2 月 6 日
table_a = readtable('https://www.mathworks.com/matlabcentral/answers/uploaded_files/1286455/Data1.xlsx')
table_a.date = datetime(table_a.year, table_a.month, table_a.day)
schoolyear = zeros(size(table_a.date));
schoolyear(isbetween(table_a.date, '01-Aug-2000', '31-Jul-2001')) = 2001;
schoolyear(isbetween(table_a.date, '01-Aug-2001', '31-Jul-2002')) = 2002;
table_a.schoolyear = schoolyear
If you have more data than just this small sample, the hard-coded statements above that set the schoolyear could be replaced with code like this:
found_years = unique(table_a.year);
for i = 1:numel(found_years)
schoolyear(isbetween(table_a.date, sprintf('01-Aug-%d', found_years(i)-1), sprintf('31-Jul-%d', found_years(i)))) = found_years(i);
end
schoolyear
6 件のコメント
その他の回答 (1 件)
John D'Errico
2023 年 2 月 6 日
編集済み: John D'Errico
2023 年 2 月 6 日
Easy peasy. :)
data = [8 7 2000 12
9 8 2000 14
9 9 2000 13
3 11 2001 11
8 3 2001 17
12 15 2001 14
2 2 2002 10
5 1 2002 9
7 3 2002 16];
You have year as the third column there. I'll call it trueyear. Just create a variable, call it schoolyear.
schoolyear = trueyear + (month >= 8);
Will that work? Of course. The school year is ALWAYS the same as the trueyear when you are in the first part of the year, so between January 1 and July 31. Once the month goes into month #8, this adds 1 to the trueyear.
There is no if statement required.
6 件のコメント
参考
カテゴリ
Help Center および File Exchange で Time Series Objects についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!