How do I write a function to convert numerical month of the year to the name of that month?
5 次查看(过去 30 天)
显示 更早的评论
I am knew to matlab and am required to write and test a function that converts numerical month of the year to the name of that month(Assuming 1=January to 12=December). I have to do 3 variations of this, one with "if", one with "else if" and the other with "switch". I would just like to know which function would be suitable to perform this operation.
0 个评论
采纳的回答
Image Analyst
2014-11-19
Hints (probably too much of a hint):
months = {'January', 'February', 'March', 'April', 'May', 'June', ...
'July', 'August', 'September', 'October', 'November', 'December'};
monthNumber = 3; % Whatever .. use inputdlg() to ask user.
if monthNumber > 1 && monthNumber < length(months)
theMonth = months{monthNumber}
end
switch monthNumber
case {1,2,3,............. You finish it!
fprintf('You picked month %s\n', months..... You finish it!
otherwise
fprintf('Invalid month number of %d', monthNumber);
end
You're going to have to finish/fix it and add the elseif to the "if" case to alert user to the invalid month. If you want to do it with 11 elseif's and check every number from 1 to 12 individually, you can do that, but it's really completely unnecessary since you can get the month with a simple index into the months array.
更多回答(1 个)
Adam Danz
2020-1-27
编辑:Adam Danz
2020-1-27
Another method to return month names given month numbers using datetime and month,
monthNames = month(datetime(1, 1:6, 1), 's')
% month numbers go here ^^^^
% monthNames =
% 1×6 cell array
% {'Jan'} {'Feb'} {'Mar'} {'Apr'} {'May'} {'Jun'}
2 个评论
Image Analyst
2020-1-27
Nifty trick. However I get them in a different order than you. I get the expected order:
monthNames =
1×6 cell array
{'Jan'} {'Feb'} {'Mar'} {'Apr'} {'May'} {'Jun'}
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Voronoi Diagram 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!