Reputation: 33
I would like to read the number 2 from the following char:
'mc_parameters.E_i = '2';'
So far, the ' '
around the number makes it a mess, because what MATLAB sees when I try to use sscanf
, textscan
and str2num
is
'mc_parameters.E_i = '2';'
and it doesn't recognize the last ';'
as a string in itself.
Any ideas?
Upvotes: 0
Views: 94
Reputation: 38032
I don't quite understand what you mean, but this one-liner works for all interpretations of your question I could think of (and then some):
cellfun(@str2double, regexp(str, ...
'[+-]?[0-9]+\.?[0-9]*(e|E|d|D)?[+-]?[0-9]*', 'match'));
where str
is your string to extract the number from.
This regular expression will find and convert all numbers in the string, in any of the following forms:
NOTE: if you only need to extract integers, a simple '[0-9]*'
will suffice :)
Examples:
>> format short e
>> f = @(str) cellfun(@str2double, regexp(str, '[+-]?[0-9]+\.?[0-9]*(e|E|d|D)?[+-]?[0-9]*', 'match'));
>>
>> str = 'mc_parameters.E_i = ''2.04''; +-8.4e-005';
>> f(str)
ans =
2.0400e+000 -8.400e-005
>> str = '2.18';
>> f(str)
ans =
2.1800e+000
>> str = '''2.21''; ''2..3e-4';
>> f(str)
ans =
2.2100e+000 2.0000e+000 3.0000e-004
Upvotes: 0
Reputation: 2359
Just use this functon :
myNum = str2num(myString);
The documentation about str2num
EDIT
I miss understood something there another thing to add :
myString = 'mc_parameters.E_i = '2';';
temp = sscanf(myString,['%[A-z.] %3c %d']);
extractNumberInString = temp(end); % Because last scanf is %d for double number.
Maybe you need to convert myString like this to execute the example :
myString = 'mc_parameters.E_i = ''2'';';
EDIT 2
Better solution is to use textscan
because with %*
you can skip some char like this :
test = textscan(myString,'%*[^''] %*c %d');
% Search until first ' and look for the white space and finish with the double number
Upvotes: 1