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.

카테고리

도움말 센터File Exchange에서 Data 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