Write a function called year2016 that returns a row-vector of struct-s whose elements correspond to the days of a month in 2016 as specified by the input argument. If the input is not an integer between 1 and 12, the function returns the empty array.
조회 수: 1 (최근 30일)
이전 댓글 표시
This is my code. Could you please tell me
function m = year2016
for i = 1:31
[MonthNumber, DateName] = weekday(datenum([2016 1:12 i]));
m.(i) = struct('month','MonthNumber','date',i,'day', DateName);
end
댓글 수: 0
채택된 답변
Stephen23
2017년 5월 26일
This code does the job (copied from my answer to this question, so this code is already in the public domain)
function out = year2016(m)
VN = datenum([2016,m,1]):datenum([2016,m+1,1])-1;
DN = 1+mod(VN-3,7);
MC = {'January';'February';'March';'April';'May';'June';'July';'August';'September';'October';'November';'December'};
DC = {'Mon','Tue','Wed','Thu','Fri','Sat','Sun'};
out = struct('day',DC(DN),'date',num2cell(1:numel(VN)));
[out(:).month] = deal(MC{m});
end
And tested:
>> m = year2016(12); m(8)
ans =
day = Thu
date = 8
month = December
>> m = year2016(1); m(1)
ans =
day = Fri
date = 1
month = January
>> m = year2016(2); m(29)
ans =
day = Mon
date = 29
month = February
>> m = year2016(4); m(1)
ans =
day = Fri
date = 1
month = April
댓글 수: 17
Levito
2018년 7월 21일
sorry, after reading the comments here I still dont understand the following things:
1 - DN - why to know the day we need the argument 1+mod(VN-3,7) ?
2 - why do we need to get 'date' as a cell (why num2cell)?
3 - why do we have to use the deal function for the month?
thank you and sorry for repeating previous questions. would be great if someone could explain these points in more detail.
Stephen23
2018년 7월 22일
편집: Stephen23
2018년 7월 22일
@Levito:
- That mod term converts the vector of serial date numbers into a vector of weekdays. Compare the values of VN and DN yourself by printing them in the command window: VN are serial data numbers (i.e. days since the imaginary day 0th Jan year 0) whereas DN are the weekdays (Monday==1).
- struct creates a structure with the same size as its input cell arrays. So to get a 1xN structure (which is what the assignment asked for) I converted the 1xN date numeric vector into a 1xN cell array using num2cell, which struct will convert into a 1xN structure.
- deal allocates one variable on the RHS (the month name) to multiple variables on the LHS (the month field of each element of the structure). In this case the LHS is defined using a comma-separated list:
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Cell Arrays에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!