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.