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.

2 views (last 30 days)
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

Accepted Answer

Stephen23
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
Levito
Levito on 21 Jul 2018
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
Stephen23 on 22 Jul 2018
Edited: Stephen23 on 22 Jul 2018
@Levito:
  1. 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).
  2. 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.
  3. 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:

Sign in to comment.

More Answers (0)

Categories

Find more on Cell Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!