patternMinor
Converting decimal to Roman numerals using MATLAB
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
endSolution
Your use of
/second version following the discussion to the other answer:
Now having the chars and numbers aligned in a data structure and using a simplified for loop.
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);
endNow 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
endfunction 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);
endContext
StackExchange Code Review Q#121126, answer score: 3
Revisions (0)
No revisions yet.