extracting numbers with different decimal extention

1 visualizzazione (ultimi 30 giorni)
Hi! I have a line in my file:
OutputY: 35,40 50 57,80 57 54,71 58,73 61,01 61,67 60,02 57,57 57,51 61,11 64,55 67,74 68,31 66,26 60,52 60,47 62,29 43,38
There some numbers have 2 decimal places and some numbers don't have it at all. When I use:
A1 = regexp(TRGT_a,'[\d*\.]*\d*','match') %TRGT_a is my variable with many columns like OutputY
it sees every number separately and instead of 20 values with decimal extension, I have 38 values... I would appreciate if you could help me to solve this? Also I will have to change all comas to fulstops to do further calculations.
Thank you in advance!

Risposta accettata

Stephen23
Stephen23 il 24 Ott 2018
Modificato: Stephen23 il 24 Ott 2018
>> S = 'OutputY: 35,40 50 57,80 57 54,71 58,73 61,01 61,67 60,02 57,57 57,51 61,11 64,55 67,74 68,31 66,26 60,52 60,47 62,29 43,38';
>> C = regexp(S,'\d+,?\d*','match');
>> V = str2double(strrep(C,',','.'))
V =
35.400 50.000 57.800 57.000 54.710 58.730 61.010 61.670 60.020 57.570 57.510 61.110 64.550 67.740 68.310 66.260 60.520 60.470 62.290 43.380
  4 Commenti
Stephen23
Stephen23 il 24 Ott 2018
Modificato: Stephen23 il 24 Ott 2018
>> S{1} = 'OutputY: 35,40 50 57,80 57 54,71 58,73 61,01 61,67 60,02 57,57 57,51 61,11 64,55 67,74 68,31 66,26 60,52 60,47 62,29 43,38';
>> S{2} = 'HelloWorld 12.34 56 7.89';
>> C = regexp(S,'\d+,?\d*','match');
>> F = @(c)str2double(strrep(c,',','.'));
>> V = cellfun(F,C,'uni',0);
>> V{:}
ans =
35.400 50.000 57.800 57.000 54.710 58.730 61.010 61.670 60.020 57.570 57.510 61.110 64.550 67.740 68.310 66.260 60.520 60.470 62.290 43.380
ans =
12 34 56 7 89
Note that your regular expression does not do what you think it does. In regular expressions, [] has a special meaning: it does NOT simply group some characters together, as you seem to be trying to do. Also there is no point in specifying to match the period character if your data uses commas.
KDRA
KDRA il 24 Ott 2018
This worked! Thanks a lot also for the explanation:) very helpful for learning!

Accedi per commentare.

Più risposte (1)

dpb
dpb il 24 Ott 2018
I'm sure there is regexp but I'm just not adept-enough w/o a lot of time and effort...the "dead-ahead" solution--
>> fmt=['Output Y:' repmat('%f',1,sum(s==9))];
>> dat=cell2mat(textscan(strrep(s,',','.'),fmt))
dat =
Columns 1 through 17
35.4000 50.0000 57.8000 57.0000 54.7100 58.7300 61.0100 61.6700 60.0200 57.5700 57.5100 61.1100 64.5500 67.7400 68.3100 66.2600 60.5200
Columns 18 through 20
60.4700 62.2900 43.3800
>>

Categorie

Scopri di più su Characters and Strings in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by