How do I write a function to convert numerical month of the year to the name of that month?
5 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jim Hamill
il 19 Nov 2014
Modificato: Adam Danz
il 27 Gen 2020
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 Commenti
Risposta accettata
Image Analyst
il 19 Nov 2014
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.
Più risposte (1)
Adam Danz
il 27 Gen 2020
Modificato: Adam Danz
il 27 Gen 2020
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 Commenti
Image Analyst
il 27 Gen 2020
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'}
Vedere anche
Categorie
Scopri di più su Voronoi Diagram in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!