need help reading only the numeric data in a value that contains letters

2 次查看(过去 30 天)
Hello,
I am trying to read in a text file where some numeric values contain letters at the end. Example text file:
487X 445X 599X 622
484 535X 568X 702E
I would like my resulting variable to only contain numbers:
myvar = [487 445 599 622;484 535 568 702];
Using the importdata command with a different file with the same type of text as the example provided above worked fine:
myfile = dir('*.txt');
mydata = importdata(myfile(1,1).name);
Can anyone tell me why this works for some files and not others and does anyone have a suggested solution?
Thanks, Dan

采纳的回答

Jan
Jan 2011-11-17
Another approach:
fid = fopen('test.txt', 'r');
if fid == -1, error('Cannot open file'); end
S = fread(fid, [1, inf], '*char');
fclose(fid);
S(S > '9') = ' ';
D = reshape(sscanf(S, '%g'), [], 4);
  1 个评论
Walter Roberson
Walter Roberson 2011-11-17
I believe you need to transpose before the reshape, as sscanf reads across the columns but reshape works down columns.

请先登录,再进行评论。

更多回答(4 个)

Fangjun Jiang
Fangjun Jiang 2011-11-17
fid=fopen('test.txt','rt');
a=textscan(fid,'%s');
b=regexp(a{1},'\d*','match');
c=cellfun(@str2double,b);
d=reshape(c,[],4)
fclose(fid);
d =
487 599 484 568
445 622 535 702

Walter Roberson
Walter Roberson 2011-11-17
NumPerLine = 4;
fid = fopen(myufile(1).name,'rt');
indata = textscan(fid, repmat('%f%*c',1,NumPerLine), 'CollectOutput',1);
fclose(fid);
mydata = indata{1};
I believe this should work even in the case where the last character on the line is a digit with no letter following before the end of line.

Dan
Dan 2011-11-17
Thanks everyone for the suggestions. Jan, your approach seems to work the best and quickest for me!
Does anyone know why my other similar file has worked using importdata?

Walter Roberson
Walter Roberson 2011-11-17
transtab = blanks(256);
transtab('0':'9') = '0':'9';
D = reshape( sscanf(transtab(fileread('test.txt')), '%g'), 4, []) .';

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by