How to transform years into centuries

2 views (last 30 days)
Radoslav Gagov
Radoslav Gagov on 13 Apr 2017
Answered: RAMAKANT SHAKYA on 7 Feb 2019
Hey guys. I need to creat a function that transforms years in to centuries. I suppose i can do it with 30 if statements, but was wandering how we can do it in a smarter way.
Write a function called centuries that takes a positive integer smaller than or equal to 3000 representing a year as its input and returns a char vector with the century the given year falls into. If the input is invalid, the function returns the empty char vector '' (there is no space between the apostrophes). Centuries are specified using roman numerals. Note that we require the shortest legal roman number. For a complete list, refer to: http://www.romannumerals.co/roman-numerals-1-to-30. Note that a century goes from year 1 to 100, so for example, the XXth century ended on December 31st, 2000. As an example, the call
>> cent = centuries(1864);
will make cent equal to ‘XIX’.
  3 Comments
Guillaume
Guillaume on 13 Apr 2017
If it works then you should submit it. It may be possible to make the conversion to roman numeral more generic but for the purpose of the assignment it's certainly good enough.
The only thing I'd change is to give meaningful names to all the variable.
Guillermo Varela Carbajal
Better to use ceil instead of floor
function cent = centuries (year)
if ~isscalar(year) || year<1 || year>3000 || year~=fix(year)
cent = '';
else
roman = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII','XVIII','XIX','XX','XXI','XXII','XXIII','XXIV','XXV','XXVI','XXVII','XXVIII','XXIX','XXX'};
cent = roman{ceil(year/100)};
end

Sign in to comment.

Answers (1)

RAMAKANT SHAKYA
RAMAKANT SHAKYA on 7 Feb 2019
function s= centuries(n)
p={'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII','XIII','XIV','XV','XVI','XVII',' XVIII','XIX','XX','XXI','XXII','XXIII','XXIV','XXV','XXVI','XXVII','XXVIII','XXIX','XXX'};
d=length(n);
if d>1
n=-1;
end
if n>0&&n<=100&&n==fix(n)
s='I'; %for less than 100
elseif n>100&&n<=3000 && n==fix(n)
m=n/100;
r=ceil(m);
s=p{r};
else
s='';
end
end

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!