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.
9 ビュー (過去 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 で Calendar についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!