Reputation: 353
I am trying to convert a cell array of strings into double so that I can use it.
hourNumbers = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'}
finHourNumbs = cell(1,length(hourNumbers))
for i=1:length(hourNumbers)
finHourNumbs {i} = str2double(hourNumbers{i});
end
I get the below output which I am NOT expecting
finHourNumbs =
Columns 1 through 9
[NaN] [NaN] [NaN] [NaN] [NaN] [NaN] [NaN] [NaN] [NaN]
Columns 10 through 12
[NaN] [NaN] [NaN]
I am expecting it to contain the strings so that I can display.
Thanks in Advance
Upvotes: 1
Views: 962
Reputation: 9864
You can use containers.Map
, and create your own roman2double
like this
hourNumbers = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'};
roman2double = containers.Map(hourNumbers, 1:12);
finHourNumbs = cell(1,length(hourNumbers));
for i=1:length(hourNumbers)
finHourNumbs {i} = roman2double(hourNumbers{i});
end
or in a shorter form
hourNumbers = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'};
roman2double = containers.Map(hourNumbers, 1:12);
finHourNumbs = values(roman2double, hourNumbers);
Upvotes: 0
Reputation: 32930
Elaborating on Gunther's solution, you're dealing with a small set of roman numbers that you need to convert to a decimal representation, so you can use a simple conversion. Here's a fast native solution with ismember
:
romans = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'};
hourNumbers = {'I', 'III', 'XII'}; %// Just a sample input data
[tf, finHourNumbs] = ismember(hourNumbers, romans);
The second output of ismember
is what you need, so just assign it to finHourNumbs
and presto!
Upvotes: 2
Reputation: 11168
A simple google search returns plenty of ways of converting a roman numeral to arabic, of which this one seems to be the simplest.
This is just for one string to convert, if you have an array of strings (in a cell array
), just use a loop or cellfun:
finHourNumbs = cellfun(@roman2arabic, hourNumbers);
OR as @EitanT points out, since you're dealing with (a small set of) hour numbers, you can also use a simple conversion array:
numsRoman = {'I','II','III','IV','V','VI','VII','VIII','IX','X','XI','XII'};
nums=1:numel(numsRoman);
and then:
finHourNumbs = cellfun(@(str) nums(strcmpi(str,numsRoman)), hourNumbers);
Upvotes: 1
Reputation: 882116
I'd be very surprised if any srt2dbl
-type conversion code recognised Roman numerals. I think you'll probably want to convert them into decimal numbers first.
The str2double
doc page states the requirements:
The string may contain digits, a comma (thousands separator), a decimal point, a leading + or - sign, an e preceeding a power of 10 scale factor, and an i for a complex unit.
If str does not represent a valid scalar value, str2double returns NaN.
No mention whatsoever of Roman numerals in there.
Upvotes: 1