Splitting number from its units
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
per isakson
2016-7-26
编辑:per isakson
2016-7-26
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 个评论
更多回答(2 个)
Image Analyst
2016-7-27
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 个评论
Azzi Abdelmalek
2016-7-26
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!