need help reading only the numeric data in a value that contains letters
조회 수: 1 (최근 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
댓글 수: 0
채택된 답변
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
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
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
댓글 수: 0
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.
댓글 수: 0
Walter Roberson
2011년 11월 17일
transtab = blanks(256);
transtab('0':'9') = '0':'9';
D = reshape( sscanf(transtab(fileread('test.txt')), '%g'), 4, []) .';
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Text Data Preparation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!