Reading numbers from alphanumeric strings in a cell matrix

1 回表示 (過去 30 日間)
shapes
shapes 2012 年 10 月 13 日
Hi ppl, i am reading a text file consisting of various lines of alpha-numeric strings...
N010 G00 X0 Y0 Z0 N020 G01 X-10 Y10 Z-1 N030 G01 X20 Y40 Z-1 N040 G04 X3 Y3 Z10 M03
Now I need all numerical values of X, i.e. -10,20,3. The problem I am facing is that the strings are read from text file as 'cell' vector and i have to convert them to 'char' to use 'regexp' using '\w*X\w*'....this works, but does not allow the negative number to be read because it starts with a '-'. What to do now??? can anybody help?? I am using MATLAB 2010
  3 件のコメント
shapes
shapes 2012 年 10 月 13 日
I'd like to carry the zero as well, but the actual numeric value is what I want to extract. And the thing is when the text file is read, it takes on line as an entity, so it is not ['N010' 'G01' 'X-10' 'Y20' 'Z5'] but ['N010 G01 X-10 Y20 Z5']...so first i break them into char, then parse but still the negative numbers are not read..
Matt Fig
Matt Fig 2012 年 10 月 13 日
See my comment on my answer below.

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

採用された回答

Matt Fig
Matt Fig 2012 年 10 月 13 日
X = {'N010' 'G00' 'X0' 'Y0' 'Z0' 'N020' 'G01'...
'X-10' 'Y10' 'Z-1' 'N030' 'G01' 'X20' 'Y40'...
'Z-1' 'N040' 'G04' 'X3' 'Y3' 'Z10' 'M03'};
N = cellfun(@str2double,regexp([X{:}],'(?<=X)-*\d+','match'))
  3 件のコメント
Matt Fig
Matt Fig 2012 年 10 月 13 日
If you have:
X = ['N010 G00 X0 Y0 Z0 N020 G01 X-10 Y10',...
'Z-1 N030 G01 X20 Y40 Z-1 N040 G04 X3 Y3 Z10 M03']
Then simply use:
N = cellfun(@str2double,regexp(X,'(?<=X)-*\d+','match'))
shapes
shapes 2012 年 10 月 13 日
Thank you very much sir..I really appreciate it... this works, I am using it for my Y and Z values as well now and it is working. Thanks again!

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 13 日
編集済み: Azzi Abdelmalek 2012 年 10 月 13 日
A={'N010' 'G00' 'X0' 'Y0' 'Z0' 'N020' 'G01' 'X-10' 'Y10' 'Z-1' 'N030'}
y=cell2mat(cellfun(@(x) str2num(cell2mat(regexp(x,'-?[0-9]','match'))),A,'un',0))
  3 件のコメント
Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 13 日
A={' N010 G00 X0 Y0 Z0 N020 G01 X-10 Y10 Z-1 N030 G01 X20 Y40 Z-1 N040 G04 X3 Y3 Z10 M03'}
y=regexp(x,'-?[0-9,.]','match')
out=cell2mat(cellfun(@(x) str2num(cell2mat(x)),y,'un',0))
shapes
shapes 2012 年 10 月 13 日
thanks again, the decimal is a little out of place but the problem is solved. Thanks again

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

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by