How to convert from Roman numeral to decimal
Show older comments
Here is the code I've devised, but the answer always comes out to 0. Any guidance would be much appreciated.
function [x]=roman2decimal(s)
s1=substring(s,1,1);
s2=substring(s,2,2);
s=substring(s,3,numel(s));
%case 1: 2 roman numbers;
numbers1=[4 9 40 90 400 900];
letters1=['I' 'I' 'X' 'X' 'C' 'C'];
letters2=['V' 'X' 'L' 'C' 'D' 'M'];
%if case 1 fails, we have case 2
numbers3=[ 1 5 10 50 100 500 1000];
letters3=['I' 'V' 'X' 'L' 'C' 'D' 'M'];
x=0;
s1=substring(s,1,1), s2=substring(s,2,2), s=substring(s,3,numel(s));
while (s~='')
case1=false;
case2=false;
i = 1;
while(i<=numel(numbers1) &~case1)
if (strcmp(s1,letters1(i)) & strcmp(s2,letters2(i)))
case1=true
x = x+numbers1(i) %update x
end
end
if(case1) %update s1, s2, s by advancing 2 characters to the right
s1=substring(s,1,1), s2=substring(s,2,2), s=substring(s,3,length(s))
else % case2
while(i<= numel(numbers3) & ~case2)
if (strcmp(s1,letters3(i))) %case2 applies % 1 letter match
case2=true
x = x+numbers3(i)%update x
end % if
end
end % if(case1)
if(case2), %update s1, s2, s by advancing 1 character to the right
s1=s2;
s2=substring(s,1,1),
s=substring(s,2,length(s));
if(~case1 && ~case2) error('Incorrect roman numeral')
end
end
end
% function [c]=substring(s,pos1,pos2)
% if(pos1 >=1 & pos2 >= pos1 & pos2 <= numel(s)) c=s(pos1:pos2);
% else c='';
% end
% end % substring
Accepted Answer
More Answers (2)
Niels
on 22 Jan 2015
0 votes
The easiest solution is to get yourself a suitable tool from the File Exchange.
It is a pretty short and straightforward code as well, so looking into it a bit may also give you some ideas on ways to approach your problem if you are (for whatever reason) not able to use the mentioned tool.
1 Comment
Madeleine
on 22 Jan 2015
Guillaume
on 22 Jan 2015
The best way to help you is to tell you to learn how to use the debugger. Your code is nearly there but there are some very simple mistakes that you would have caught straight away had you stepped through the code.
So set a breakpoint on the first line of your code. Call your function and step through it line by line. You'll quickly see that:
- the condition of your first while loop is wrong. For a start it should be
~strcmp(s, '')
but also you stop it too early and will never process the last two characters of your input. You need to change the point at which you modify s
- you never increment i in your other two while loops, hence they run forever
- you never reset case1 and case2 to false.
The last two bugs are trivial to fix, the only one that is a bit trickier is getting the end condition of you main while loop correct. Fix that one, and your code works. You can then come back here and I'll show you how to make it more efficient.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!