Splitting number from its units
4 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
per isakson
on 26 Jul 2016
Edited: per isakson
on 26 Jul 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 Comments
More Answers (2)
Image Analyst
on 27 Jul 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 Comments
Azzi Abdelmalek
on 26 Jul 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 Comments
See Also
Categories
Find more on Whos 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!