need help reading only the numeric data in a value that contains letters
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuesta aceptada
Jan
el 17 de Nov. de 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 comentario
Walter Roberson
el 17 de Nov. de 2011
I believe you need to transpose before the reshape, as sscanf reads across the columns but reshape works down columns.
Más respuestas (4)
Fangjun Jiang
el 17 de Nov. de 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
0 comentarios
Walter Roberson
el 17 de Nov. de 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.
0 comentarios
Walter Roberson
el 17 de Nov. de 2011
transtab = blanks(256);
transtab('0':'9') = '0':'9';
D = reshape( sscanf(transtab(fileread('test.txt')), '%g'), 4, []) .';
0 comentarios
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!