Mal*_*ina 7 file-io matlab text-files
我在读取包含10列和2行标题的txt文件时遇到问题,但问题是在文件中间,相同的标题会多次出现并且textread()不起作用.这是我的文件示例:
headerline1 aaaa
headerline2 111 123
20/12/2000 name1 name2 name3... name8 0
21/12/2000 name1 name2 name3... name8 0
22/12/2000 name1 name2 name3... name8 0
headerline1 aaaa
headerline2 111 123
25/12/2000 name1 name2 name3... name8 0
27/12/2000 name1 name2 name3... name8 0
...
Run Code Online (Sandbox Code Playgroud)
这是我试过的代码:
[date, name1, name2, name3, name4, name5, name6, name7, name8, status] = ...
textread('file.txt', '%s %s %s %s %s %s %s %s %s %d', 'headerlines',2);
Run Code Online (Sandbox Code Playgroud)
它会在重复的标题行中准确地给出错误.你有什么想法我怎么能避免这些标题并阅读完整的文件?问题是我有数百种这类文件,所以我不能每次都手动删除.
感谢帮助.
您可以先将textscan整行作为字符串逐行读取文件.然后删除标题行,并处理其余内容
这是一个例子:
%# read the whole file to a temporary cell array
fid = fopen(filename,'rt');
tmp = textscan(fid,'%s','Delimiter','\n');
fclose(fid);
%# remove the lines starting with headerline
tmp = tmp{1};
idx = cellfun(@(x) strcmp(x(1:10),'headerline'), tmp);
tmp(idx) = [];
%# split and concatenate the rest
result = regexp(tmp,' ','split');
result = cat(1,result{:});
%# delete temporary array (if you want)
clear tmp
Run Code Online (Sandbox Code Playgroud)