Splitting number from its units
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Sowmya MR
le 26 Juil 2016
Réponse apportée : Image Analyst
le 27 Juil 2016
HI, I have a cell array with following values:
'1mcg/kg'
'1mcg/kg'
'1mcg/kg'
'0.7mcg/kg/hr'
'0.7mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'
How do i split this into numbers and units? I need the output in two cell arrays something like:
'1' 'mcg/kg'
'1' 'mcg/kg'
'0.7' 'mcg/kg/hr'
'0.5' 'mcg/kg/hr'
0 commentaires
Réponse acceptée
per isakson
le 26 Juil 2016
Modifié(e) : per isakson
le 26 Juil 2016
Try
>> cac = regexp( '0.7mcg/kg/hr', '([\d\.]+)|(\D+)', 'tokens' );
>> cac{:}
ans =
'0.7'
ans =
'mcg/kg/hr'
>> cac = regexp( '0.7mcg/kg/hr', '([\d\.]+)|(\D+)', 'match' );
>> cac{:}
ans =
0.7
ans =
mcg/kg/hr
>>
Note: Numbers in the unit string will cause problems
 
This returns leading digits and dots as the value and the rest of the string as the unit.
>> cac = regexp( '0.7mcg2/kg/hr', '\<([\d\.]+)(.+)\>', 'tokens' );
>> cac{:}
ans =
'0.7' 'mcg2/kg/hr'
>>
Whatever mcg2 stands for.
And as Azzi shows regexp takes a cell array of strings in place of a single string.
0 commentaires
Plus de réponses (2)
Image Analyst
le 27 Juil 2016
As an alternative, if you don't understand the cryptic regexp commands, then you can use a simple "for" loop:
ca = {'1mcg/kg'
'1mcg/kg'
'1mcg/kg'
'0.7mcg/kg/hr'
'0.7mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'}
for k = 1 : length(ca)
thisString = ca{k}; % Extract this string
% Find where the units start. They will start with a letter.
firstNonNumberIndex = find(thisString >= 'A', 1, 'first');
% Extract numbers and units into two cell arrays.
numbers{k} = str2double(thisString(1:firstNonNumberIndex-1));
units{k} = thisString(firstNonNumberIndex:end);
end
% Show them in the command window
celldisp(numbers);
celldisp(units);
I'd really recommend though that you don't use a cell array for the numbers and use it only for the units. Use a regular numerical double array for the numbers.
0 commentaires
Azzi Abdelmalek
le 26 Juil 2016
str={'1mcg/kg'
'1mcg/kg'
'1mcg/kg'
'0.7mcg/kg/hr'
'0.7mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'
'0.5mcg/kg/hr'}
v1=regexp(str,'[\d\.]+','match','once')
v2=regexpi(str,'[a-z\/]+','match','once')
0 commentaires
Voir également
Catégories
En savoir plus sur Characters and Strings dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!