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

2 views (last 30 days)
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

Accepted Answer

Jan
Jan on 17 Nov 2011
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 Comment
Walter Roberson
Walter Roberson on 17 Nov 2011
I believe you need to transpose before the reshape, as sscanf reads across the columns but reshape works down columns.

Sign in to comment.

More Answers (4)

Fangjun Jiang
Fangjun Jiang on 17 Nov 2011
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 on 17 Nov 2011
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 on 17 Nov 2011
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 on 17 Nov 2011
transtab = blanks(256);
transtab('0':'9') = '0':'9';
D = reshape( sscanf(transtab(fileread('test.txt')), '%g'), 4, []) .';

Community Treasure Hunt

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

Start Hunting!