Read text file - ignoring lines starting with specific character.

29 visualizaciones (últimos 30 días)
Billy
Billy el 1 de Oct. de 2019
Respondida: Stephen23 el 1 de Oct. de 2019
I have a text file with 17 columns of numeric data separated by a double space. These are preceded by some number of lines starting with the '#' symbol. I would like to discard all lines starting with '#' and only read the numeric data, but these numbers need to be read in as strings. How do I ignore all lines starting with '#' and only read the remaining lines as strings?
The text file is of the form (but with more columns):
# filename
# date and time
# some more info
1.111111111 2.222222222 3.333333333 4.444444444 ...
1.111111112 2.222222223 3.333333334 4.444444445 ...

Respuestas (2)

Jon
Jon el 1 de Oct. de 2019
Editada: Jon el 1 de Oct. de 2019
I'm not sure why you would want to read in numerical data as strings.
You can read in the data in your files using (assuming for example your file is called myfile.csv)
A = readmatrix('myfile.csv','Delimiter',' ')
note that you seem to have two spaces between your values so it is ' ', not ' ' as the delimiter.
If you really want them to be strings, you can alway change them into strings after you read them in as numbers, using for instance
Astr = num2str(A)
If for some reason readmatrix is confused about some of the initial header lines (the ones you shouw starting with #, if you know how many header lines you can also specify that for example, for 3 header lines as you show in your listing
A = readmatrix('myfile.csv','Delimiter,' ',NumHeaderLines',3)

Stephen23
Stephen23 el 1 de Oct. de 2019
nmc = 4; % number of columns in file
fmt = repmat('%f',1,nmc);
opt = {'HeaderLines',3, 'CollectOutput',true, 'MultipleDelimsAsOne',true};
%
[fid,msg] = fopen('test.txt','rt');
assert(fid>=3,msg)
C = textscan(fid,fmt,opt{:});
fclose(fid);
M = C{1}
giving:
M =
1.111111111000000 2.222222222000000 3.333333333000000 4.444444444000000
1.111111112000000 2.222222223000000 3.333333334000000 4.444444445000000

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by