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!