How to read formatted data from string in matlab?

238 Views Asked by At

I have cell array of strings with different values:

v = {'12.4B', '145.3M', '34.3M', '1.2B'};

I would like to convert them to numbers. Using sscanf function I can extract only numeric values, but what I want is to multiply the result by billion or million according to the letter.

2

There are 2 best solutions below

4
On BEST ANSWER

You can replace B and M with e9 and e6 respectively (scientific notation) using regular expression replacement (regexp) and then convert the resulting strings to a number with str2double.

out = str2double(regexprep(v, {'B', 'M'}, {'e9', 'e6'}, 'ignorecase'))

You can obviously expand this to include any other necessary conversions.

And as an example showing what's happening:

% Convert to scientific notation
B = regexprep(v, {'B', 'M'}, {'e9', 'e6'}, 'ignorecase')
%    '12.4e9'    '145.3e6'    '34.3e6'    '1.2e9'

% Convert to numbers
str2double(B)
%   12400000000 145300000   34300000    1200000000
0
On
% Data
v = {'12.4B', '145.3M', '34.3M', '1.2B'};

% Replace characters with numeric equivalents
v = strrep(v, 'k', 'e03'); % thousand
v = strrep(v, 'M', 'e06'); % Million
v = strrep(v, 'B', 'e09'); % Billion 
v = strrep(v, 'T', 'e12'); % Trillion 
...

% Convert to numeric values
w = str2double(v)