Read text file - ignoring lines starting with specific character.
31 次查看(过去 30 天)
显示 更早的评论
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 ...
0 个评论
回答(2 个)
Jon
2019-10-1
编辑:Jon
2019-10-1
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)
0 个评论
Stephen23
2019-10-1
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!