フィルターのクリア

Splitting number from its units

2 ビュー (過去 30 日間)
Sowmya MR
Sowmya MR 2016 年 7 月 26 日
回答済み: Image Analyst 2016 年 7 月 27 日
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'

採用された回答

per isakson
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
&nbsp
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.

その他の回答 (2 件)

Image Analyst
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.

Azzi Abdelmalek
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')

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by