How to parse text to numbers?
1 次查看(过去 30 天)
显示 更早的评论
Hi
I have text cell str looking like this? Is there a way to use regexp to convert this matrix?
ttxt = {'No info','1-50.00000','3-100.000','2-2.0000','Free & Unlimited', '1-100.0000;1-0.0000','1-25.000;1-50.000'}';
ttxt =
{'No info' }
{'1-50.00000' }; % one with 50%
{'3-100.000' } % three with 100% each
{'2-2.0000' } % two with 2% each
{'Free & Unlimited' } % three with 0%
{'1-100.0000;1-0.0000'} % two with first one 100% and 2nd one is 0%
{'1-25.000;1-50.000' } % two with first one 25% and 2nd one 50%
The rules are basically:
when the text is 'No info', it means there are no info, so it returns [0 0 0 0]
When the text is 'Free & Unlimited', it returns [3 0 0 0]
For other cases, there are 2 patterns:
- first number > 1: 3-100... or 2-2.00, the first number tells number of repeated %. in this case there are 3 100% and 2 2%, respectively. So it should be [3 1 1 1] and [2 0.02 0.02 0]
- multiple cell with ';' {'1-25.00;1-50.00'}; this means there are 2 data with first one is 25%, and 2nd one is 50%, so it should return [2 0.25 0.50 0.0]
want the output matrix to be
tdata = [0 0 0 0;
1 0.5 0 0;
3 1 1 1;
2 0.02 0.02 0;
3 0 0 0;
2 1 0 0;
2 0.25 0.5 0];
2 个评论
Adam Danz
2020-8-5
Very unclear.
Please explicitly state each rule that translates a row of text to a row of values in the matrix.
采纳的回答
Stephen23
2020-8-5
编辑:Stephen23
2020-8-5
>> ttxt = {'No info';'1-50.00000';'3-100.000';'2-2.0000';'Free & Unlimited';'1-100.0000;1-0.0000';'1-25.000;1-50.000'}
ttxt =
'No info'
'1-50.00000'
'3-100.000'
'2-2.0000'
'Free & Unlimited'
'1-100.0000;1-0.0000'
'1-25.000;1-50.000'
>> fun = @(s)sscanf(s,'%f-%f;',[2,Inf]);
>> out = cellfun(fun,ttxt,'uni',0);
>> idx = ~cellfun(@isempty,out);
>> baz = @(m,n)[n,repelem(m(2,:)./100,m(1,:)),zeros(1,3-n)];
>> foo = @(m)baz(m,sum(m(1,:)));
>> out(idx) = cellfun(foo,out(idx),'uni',0);
>> out(strncmpi(ttxt,'No',2)) = {[0,0,0,0]};
>> out(strncmpi(ttxt,'Fr',2)) = {[3,0,0,0]};
>> mat = vertcat(out{:})
mat =
0 0 0 0
1.0000 0.5000 0 0
3.0000 1.0000 1.0000 1.0000
2.0000 0.0200 0.0200 0
3.0000 0 0 0
2.0000 1.0000 0 0
2.0000 0.2500 0.5000 0
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!