Wednesday 15 January 2014

Matlab convert integer to roman -



Matlab convert integer to roman -

i trying convert integer x (0<=x<=3999) roman numeral y.

i wrote codes this, maintain getting error when run. problem of code?

c1=['','m','mm','mmm']; c2=['','c','cc','ccc','d','dc','dcc','dccc','cm']; c3=['','x','xx','xxx','xl','l','lx','lxx','lxxx','xc']; c4=['','i','ii','iv','v','vi','vii','viii','ix']; x=0; i4=1:4; i3=1:9; i2=1:9; i1=1:9; if x==0 y=''; else y=[c1{i4} c2{i3} c3{i2} c4{i1}]; x=x+1; end end end end end

based on this post, here matlab version:

function str = num2roman(x) assert(isscalar(x) && floor(x)==x); assert(1 <= x && x <= 3999); numbers = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]; letters = {'m', 'cm', 'd', 'cd', 'c', 'xc', 'l', 'xl', 'x', 'ix', 'v', 'iv', 'i'}; str = ''; num = x; i=1:numel(numbers) while (num >= numbers(i)) str = [str letters{i}]; num = num - numbers(i); end end end

here whole range of numbers converted roman numerals:

>> x = (1:3999).'; >> xx = arrayfun(@num2roman, x, 'uniformoutput',false); >> table(x, xx, 'variablenames',{'integer','roman_numeral'}) ans = integer roman_numeral _______ _________________ 1 'i' 2 'ii' 3 'iii' 4 'iv' 5 'v' 6 'vi' 7 'vii' 8 'viii' 9 'ix' 10 'x' . .

matlab roman-numerals

No comments:

Post a Comment