Extracting non-alphabets from a string

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 件のコメント

Raunak
Raunak 2014 年 12 月 7 日
I am now using N = cellfun(@str2double,regexp(Str,'(?<=X).*(?=[A-Z])','match')) which works for all except F because it is the end. Is there a way to specify end of string?

サインインしてコメントする。

 採用された回答

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 12 月 7 日

0 投票

Str='G02X56.32Y13.05Z4.5F0.1'
str2double(regexp(Str,'\d+(\.\d+)?','match'))

1 件のコメント

Raunak
Raunak 2014 年 12 月 8 日
Actually (regexp(Str,'(?<=X)\d+(\.\d+)?','match')) works perfectly! Thank you! :)

サインインしてコメントする。

その他の回答 (1 件)

Geoff Hayes
Geoff Hayes 2014 年 12 月 8 日

0 投票

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 件のコメント

Raunak
Raunak 2014 年 12 月 8 日
Thanks a lot. This solved the problem!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

質問済み:

2014 年 12 月 7 日

コメント済み:

2014 年 12 月 8 日

Community Treasure Hunt

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

Start Hunting!

Translated by