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.
5 views (last 30 days)
Show older comments
Wasi von Deutschland
on 26 May 2017
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 Comments
Accepted Answer
Stephen23
on 26 May 2017
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 Comments
Stephen23
on 22 Jul 2018
Edited: Stephen23
on 22 Jul 2018
@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:
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!