Reading varying headerlines length, text files

조회 수: 2 (최근 30일)
Matlab User
Matlab User 2016년 8월 23일
편집: Matlab User 2016년 8월 29일
Hi, I am trying to read specific part of the header lines for these files and once I read lines i want to increment for each block and display them into GUI edit text boxes.
fid= fopen([FilesToRead, MultipleFiles]);
textForGUI = cell(1);
while true
tLine = fgetl(fid);
headerCells = strsplit(tLine,' ');
if length(headerCells) > 1
if ~isempty(headerCells{2})
if ~strcmpi(headerCells{2},'!User') && ~strcmpi(headerCells{2},'data')
textForGUI(end+1) = headerCells(2);
else
break
end
end
end
end
textForGUI = textForGUI(2:end);
Block=0;
while true
tLine = fgetl(fid);
if ~ischar(tLine)
break;
end
if ~isempty(strfind(tLine,'data'))
Block=Block+1;
if true
% code
end
formatSpec = '%f %f %f %f %f';
C = textscan(fid,formatSpec,24,'CommentStyle','data','Delimiter','\t');
%here I got some calculations and plots
end
end
Thanks!
  댓글 수: 1
Matlab User
Matlab User 2016년 8월 23일
편집: Matlab User 2016년 8월 29일
Any help on this question please?

댓글을 달려면 로그인하십시오.

채택된 답변

Kelly Kearney
Kelly Kearney 2016년 8월 23일
I usually find the easiest way to do this sort of thing is to read the whole file in as plain text (assuming it's not too large), and then parsing out the bits I want using strfind and regexp as appropriate. Here's an example:
fid = fopen('~/Downloads/Example-2.txt');
tmp = textscan(fid, '%s', 'delimiter', '\n', 'whitespace', '');
tmp = tmp{1};
fclose(fid);
% Figure out where each header section begins and ends
sidx = find(~cellfun('isempty', regexp(tmp, '^\d*\s*\*\*\*letter')));
eidx = find(~cellfun('isempty', regexp(tmp, '^\d*\s*high')));
% Assume data runs from end of one header to beginning of next
dsidx = eidx + 1;
deidx = [sidx(2:end)-1; length(tmp)];
% Loop over blocks
nblock = length(sidx);
C = cell(nblock,1);
textForGUI = cell(nblock,1);
for ii = 1:nblock
% Read the header block and data block
headerlines = tmp(sidx(ii):eidx(ii));
datalines = tmp(dsidx(ii):deidx(ii));
% Throw away the data lines you don't need (!user, data, blank)
datalines = regexprep(datalines, '^\d*', '');
isgood = cellfun('isempty', strfind(datalines, '!user')) & ...
cellfun('isempty', strfind(datalines, 'data')) & ...
~cellfun('isempty', strtrim(datalines));
datalines = sprintf('%s\n', datalines{isgood});
% Read numbers from cleaned-up data block
formatSpec = '%f %f %f %f %f';
C{ii} = textscan(datalines,formatSpec,24,'CommentStyle','data','Delimiter','\t');
textForGUI{ii} = headerlines(2:end);
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by