How to parse text to numbers?
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Adam Danz
le 5 Août 2020
Very unclear.
Please explicitly state each rule that translates a row of text to a row of values in the matrix.
Réponse acceptée
Stephen23
le 5 Août 2020
Modifié(e) : Stephen23
le 5 Août 2020
>> 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
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Data Type Conversion dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!