2014-10-05 63 views
3

我有,看起来像一个数据文件:在Octave/MATLAB中读取csv文件时,我可以忽略注释行吗?

# data file 
# blah 
# blah 

     0.000000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.020000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.040000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.060000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.080000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.100000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 
     0.120000, 0.0, 24.198, 6.864,NaN,NaN,NaN,NaN 

,我想用一个八度程序来读取它。

csvread(文件,3,0)在这种情况下完美地工作,但我担心必须手工制定3。

是否有某种方式可以说'在执行csvread之前丢掉以#开始的所有行,以及任何空白行?

回答

4

在八度,你可以做

d = load("yourfile") 

应该忽略#线

编辑: 文件类型的上述用途的自动检测,你也可以强迫它d = load ("-ascii", "yourfile").来自help load的报价:

'-ascii' 
     Force Octave to assume the file contains columns of numbers in 
     text format without any header or other information. Data in 
     the file will be loaded as a single numeric matrix with the 
     name of the variable derived from the name of the file. 

不幸的是,该帮助没有提及以%或#开头的行被忽略。为此,您必须查看源代码(幸运的是自从GNU Octave是自由软件以来)get_mat_data_input_line from octave source

从那里你可以看到跳过%或#之后的所有字符。

+1

非常简单,快速,谢谢!希望我在写我的之前看到了你的答案...... – ederag 2014-10-06 10:50:30

+0

哇,有没有这方面的文档? – 2014-10-06 16:14:47

+0

@JohnLawrenceAspden https://www.gnu.org/software/octave/doc/interpreter/Simple-File-I_002fO.html,似乎它默认为“-ascii” – ederag 2014-10-06 17:28:06

3

csvread不允许使用此选项。相反,您可以使用textscan,但是,您需要知道csv文件有多少列(或多行)。

例如:

fid = fopen('csvFile.csv','r'); 
c = textscan(fid,'%f','commentStyle','#','delimiter',','); 
fclose(fid); %# close the file as soon as we don't need it anymore 

array = reshape([c{:}],[],7)'; 
1

这是一种跳过以注释字符串开头的标题行的方法。 csvread行可以由dlmread呼叫除','以外的分隔符替换。这两个函数的速度都比倍频程3.8.2上的textscan快得多。

fid = fopen('csvFile.csv','r'); 

comment = '#'; 
while strcmp(fgets(fid, length(comment)), comment) 
    % line begins with a comment, skip it 
    fskipl(fid); 
endwhile 
% get back, because the last read length(comment) characters 
% are not comments, actually 
fseek(fid, -length(comment), SEEK_CUR); 

c = csvread(fid); 

fclose(fid); 
相关问题