Splitting number from its units
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Sowmya MR
el 26 de Jul. de 2016
Respondida: Image Analyst
el 27 de Jul. de 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 comentarios
Respuesta aceptada
per isakson
el 26 de Jul. de 2016
Editada: per isakson
el 26 de Jul. de 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 comentarios
Más respuestas (2)
Image Analyst
el 27 de Jul. de 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 comentarios
Azzi Abdelmalek
el 26 de Jul. de 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 comentarios
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!