Write and Test 3 functions to convert month number to month name

1 view (last 30 days)
Write and test 3 MATLAB functions month2nameA, month2nameB, month2nameC
to convert the numerical month of the year into the name of that month.
Assume 1=January to 12=December. and use a set of only "if" statements for month2nameA use a set of "elseif" statements for month2nameB use a "switch" statement for month2nameC.
I then have to write a test script called TestMonths which uses a for loop, to display all
the names from each function month2nameA, month2nameB, month2nameC.
The name of each month should appear together 3 times (I.e. once for each
function, then move to the next month in the list/loop).
My first function i think is something along the lines of:
function [months] = month2nameA (MonthNumber)
months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'};
monthNumber = 3;
if monthNumber > 1 && monthNumber < length(months)
theMonth = months{monthNumber}
end
My second function is:
function [months] = month2nameB (MonthNumber)
months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'};
monthNumber = ;
if monthNumber > 1 && monthNumber < length(months)
theMonth = months{monthNumber};
elseif monthNumber == 1
theMonth = 'January';
elseif monthNumber == 12
theMonth = 'December';
else
theMonth = 'Invalid Month Number'
end
end
My 3rd function is
function [months] = month2namec (MonthNumber)
switch (monthNumber);
case {1,2,3,4,5,6,7,8,9,10,11,12};
fprintf('You picked month %s\n', months{'January', 'February'...
'March', 'April', 'May', 'June', 'July', 'August', 'September'...
'October', 'November', 'December'});
otherwise
fprintf('Invalid month number of %d', monthNumber);
end
end
I know none of these are exactly correct but could anyone help where I am going wrong in these, and how I would construct these functions correctly to test them and then be able to put them in the 'for' loop.
Thank you.

Answers (1)

Star Strider
Star Strider on 20 Nov 2014
You need to correct the logic in your if statement to allow January and December:
monthNumber >= 1 && monthNumber <= length(months)
replacing ‘>’ with ‘>=’ and ‘<’ with ‘<=’ respectively. The others I didn’t test.
  2 Comments
Jim Hamill
Jim Hamill on 20 Nov 2014
Oh yea thanks, I meant to have it that way for my second function because I was not sure what I could use an 'elseif' statement for in the second function
Star Strider
Star Strider on 20 Nov 2014
My pleasure!
You need to be sure to include that logic in your first two functions. The third uses a different approach, so it’s safe.

Sign in to comment.

Categories

Find more on Graphics Object Programming 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!