HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Converting decimal to Roman numerals using MATLAB

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
romanmatlabdecimalusingnumeralsconverting

Problem

I have written a MATLAB function that converts decimals into Roman numerals.

function ans = dec2rom(z)
d = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
c =  {'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
[];
for ii = 1:numel(d)
    if z >= d(ii)    
        ans = [ans,repmat(c{ii},1,fix(z/d(ii)))];
        z = rem(z,d(ii));
    end
end

Solution

Your use of ans is very difficult to understand, it took me 5 minutes reading the lines to understand what []; really does and why it is necessary.

function r = dec2rom(z)
d = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
c =  {'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = 1:numel(d)
    if z >= d(ii)    
        r = [r,repmat(c{ii},1,fix(z/d(ii)))];
        z = rem(z,d(ii));
    end
end


/second version following the discussion to the other answer:

function r = dec2rom(z)

t={ 1000, 900, 500,  400, 100,   90,  50,   40,  10,    9,   5,    4,   1;
    'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = t
    num = ii{1};
    symb = ii{2};
    r = [r,repmat(symb,1,fix(z/num))];
    z = rem(z,num);
end


Now having the chars and numbers aligned in a data structure and using a simplified for loop.

Code Snippets

function r = dec2rom(z)
d = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
c =  {'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = 1:numel(d)
    if z >= d(ii)    
        r = [r,repmat(c{ii},1,fix(z/d(ii)))];
        z = rem(z,d(ii));
    end
end
function r = dec2rom(z)

t={ 1000, 900, 500,  400, 100,   90,  50,   40,  10,    9,   5,    4,   1;
    'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'};
r='';
for ii = t
    num = ii{1};
    symb = ii{2};
    r = [r,repmat(symb,1,fix(z/num))];
    z = rem(z,num);
end

Context

StackExchange Code Review Q#121126, answer score: 3

Revisions (0)

No revisions yet.