I need help extracting block data from text files.

2 views (last 30 days)
I need to compile data from a number of text files; I think textscan is the appropriate function, but I'm fairly new to Matlab and struggling to get started writing scripts. The files I'm working with are in block format (see attached for a simple example). Both headers and data tables are repeated at regular intervals. For the attached example, note that the very first header line can be discarded, and then the blocks repeat at consistent intervals. I want to create two vectors: one to track the model number and one to track the value (both in the first of the two repeated headers). And, somehow, extract all of the 6 x 2 tables in a way such that I can link each table to its respective model number and value. If any of you more experienced Matlab users can help me get started with this by providing an example script or any sort of insight, I would very much appreciate it!
  2 Comments
dpb
dpb on 11 Jan 2014
No sample posted.
NB: however that you can call textscan in a loop to reapply the same format multiple times for such structured files. If these blocks are the same size or at least have a header that identifies how may lines are in each block this is essentially trivial.
It would seem associating a value with each block should be pretty much just a 1:1 correlation; if you were to use a cell array to hold the individual "blocks" as cell array entry contents.
Trent
Trent on 14 Jan 2014
Sorry about that, dpb. The file should now be attached -- thank you for your comment.

Sign in to comment.

Accepted Answer

dpb
dpb on 15 Jan 2014
Caution--air code, not tested...
As suggested earlier, use textscan in a loop. I'd put in a function with an internal function to handle the block more concisely...sotoo
[id,dat]=readblockfile(filename)
fid=fopen(filename); % add error handling, etc.
fgetl(fid); % throw away the one header line
n=0; % initialize a counter
while ~feof(fid) % start an indefinite loop
n=n+1;
[id(n), dat{n)=getblkdat(fid);
end
[id,dat]=function getblkdat(fid)
id=textscan(fid,'# Layered model %d: value=%f');
dat=textscan(fid,'%f %f',6,'collectoutput','true');
end
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!