Extracting non-alphabets from a string
Afficher commentaires plus anciens
I have a string of the form Str='G02X56.32Y13.05Z4.5F0.1'
I want to extract x=56.32, Y=13.05 etc. The orders of X and Y can be interchanged. How do I extract non-alphabetical characters in between two alphabets?
I use N = cellfun(@str2double,regexp(Str,'(?<=X)-*\d+','match')) and I get only 56 instead of 56.32. Please help me! Thanks!
1 commentaire
Raunak
le 7 Déc 2014
Réponse acceptée
Plus de réponses (1)
Geoff Hayes
le 8 Déc 2014
Raunak - when I run your above code I either see (for the first case) just the output of 56, and in the second example, a value of NaN.
Why not just split the string on the alphabetic characters? Something like
>> [numericChars,alphabeticIdcs] = regexp(Str,'[A-Z]','split')
numericChars =
'' '02' '56.32' '13.05' '4.5' '0.1'
alphabeticIdcs =
1 4 10 16 20
So we split the string into its numeric and alphabetic parts (with the latter giving us the indices of the characters A through Z). We can then map these alphabetic characters as fields in a structure where each field gives us the numeric value. Something like
fields = arrayfun(@(x)Str(x),alphabeticIdcs)';
n = size(fields,1);
data = cell2struct(mat2cell(str2double(numericChars(2:end))',ones(1,n)),fields);
where
data =
G: 2
X: 56.32
Y: 13.05
Z: 4.5
F: 0.1
In the above code, we create the cell array of field names, fields, and then take the transpose of it so that we have an nx1 array. We then supply to cell2struct two cell arrays - the fields and the numeric data that has been converted into doubles and then reshaped into a cell array (from a matrix) using mat2cell.
The above may be a few more lines than you want, but it does nicely (?) map the alphabetic character to a numeric value, without caring about the order of X,Y, etc. Note that the code assumes that that a single alphabetic character separates each numeric input.
1 commentaire
Raunak
le 8 Déc 2014
Catégories
En savoir plus sur Data Type Conversion dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!