Search code examples
matlabroman-numerals

Matlab convert integer to roman


I am trying to convert integer x (0<=x<=3999) to Roman numeral y.

I wrote codes for this, but I keep getting an error when I run. What is a problem of this 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;
for i4=1:4;
    for i3=1:9;
        for i2=1:9;
            for 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

Solution

  • Based on this post, here is a 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;
        for i=1:numel(numbers)
            while (num >= numbers(i))
                str = [str letters{i}];
                num = num - numbers(i);
            end
        end
    end
    

    Here is the whole range of numbers converted to 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'       
           .
           .