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
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 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!