using readtable function except for last five lines from text file

11 次查看(过去 30 天)
for i=1:2
line_check{i,:} = regexp(fileread(full_file_name(i,:)),'\n','split');
end_of_header_line(i) = find(contains(line_check{i,:},'++Coordinate'));
end
for j=1:2
tCOD{j,:}=readtable(full_file_name(j,:),'FileType','text', ...
'headerlines',end_of_header_line(j),'readvariablenames',0);
end
The above codes worked with the attached file without the last five lines. If the last five lines does not deleted, the codes give "All lines of a text file must have the same number of delimiters" error. How I can use readtable without reading the the last five lines from text file?

采纳的回答

Simon Chan
Simon Chan 2021-8-14
编辑:Simon Chan 2021-8-14
Use your similar method to detect the last line of the valid data and add some import options as follows:
for i=1:2
line_check{i,:} = regexp(fileread(full_file_name(i,:)),'\n','split');
end_of_header_line(i) = find(contains(line_check{i,:},'++Coordinate'));
end_of_data_line(i) = find(contains(line_check{i,:},'--Coordinate')); % Added this line
end
% Add some import options
for j=1:2
opts = detectImportOptions(fileread(full_file_name(j,:));
opts.DataLines=[end_of_header_line(j)+1 end_of_data_line(j)-1]; % Valid data line
% Following two lines are optional, depends on what format you want
%opts.Delimiter={' '};
%opts.ConsecutiveDelimitersRule='join';
tCOD{j,:}=readtable(full_file_name(j,:),opts);
end
  2 个评论
Simon Chan
Simon Chan 2021-8-15
Try the following, also find some typo in my previous code and hence revised as follows:
for i=1:2
line_check{i,:} = regexp(fileread(full_file_name(i,:)),'\n','split');
end_of_header_line(i) = find(contains(line_check{i,:},'++Coordinate'));
end_of_data_line(i) = find(contains(line_check{i,:},'--Coordinate')); % Added this line
end
% Add some import options
for j=1:2
opts = detectImportOptions(full_file_name(j,:)); % Revised this line
opts.DataLines=[end_of_header_line(j)+1 end_of_data_line(j)-1]; % Valid data line
opts.Delimiter={' '};
opts.LeadingDelimitersRule='ignore';
opts.ConsecutiveDelimitersRule='join';
tCOD{j,:}=readtable(full_file_name(j,:),opts);
xyz{j,:}=tCOD{j,:}(:,16:18);
end
The output is a 3 columns matrix with 86,388 rows, hope this is what you want.
The header has offset by 3 columns and hence the header name starts from 13 until 15.

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

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

Start Hunting!

Translated by