Path: news.mathworks.com!newsfeed-00.mathworks.com!panix!bloom-beacon.mit.edu!senator-bedfellow.mit.edu!dreaderd!not-for-mail
From: Arthur G <gorramfreak+news@gmail.com>
Newsgroups: comp.soft-sys.matlab
Date: Sat, 15 Mar 2008 15:48:37 -0400
Message-ID: <47dc2815$0$289$b45e6eb0@senator-bedfellow.mit.edu>
References: <frgs93$1ov$1@fred.mathworks.com>
MIME-Version: 1.0
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8bit
Subject: Re: how to read text file row/column info
User-Agent: Unison/1.8
Lines: 62
NNTP-Posting-Host: VPN-ONE-SEVENTY-EIGHT.MIT.EDU
X-Trace: 1205610517 senator-bedfellow.mit.edu 289 18.100.0.178
Xref: news.mathworks.com comp.soft-sys.matlab:457422



On 2008-03-15 12:08:03 -0400, "Bruce Eddy" <sailboats@cfl.rr.com> said:

> "Pekka " <pekka.nospam.kumpulainen@tut.please.fi> wrote in
> message <frg668$im6$1@fred.mathworks.com>...
>> "Bruce Eddy" <sailboats@cfl.rr.com> wrote in message
>> <frfjcc$it5$1@fred.mathworks.com>...
>>> Hi,
>>> I am trying to read a large .txt file with 5 columns
> and
>>> over 12000 rows of data.  I'm having trouble getting
> the
>>> (row, column) numbers right.  The code looks like this;
>>> 
>>> loop = 0;
>>> for i = 1:2
>>> line1 = fgets(fid);
>>> end
>>> while feof(fid) == 0
>>> loop = loop+1;
>>> line1 = fgets(fid);
>>> mass_prop(loop).name = line1(1, 1: 66);
>>> mass_prop(loop).matl = line1(1,67: 102);
>>> mass_prop(loop).volm = line1(1,103: 119);
>>> mass_prop(loop).dens = line1(1,120:133);
>>> mass_prop(loop).wght = line1(1,134:149);
>>> end
>>> 
>>> Can anyone help?
>>> Thanks.
>> 
>> Really hard to help much without knowing the structure of
>> your file. Hard coding the indexing is generally not a
> good
>> idea. That will fail if any of the lines has different
>> length in any of the fields.
>> 
>> Take a look at
>> doc textscan
>> that should read the entire file wthout loops and hard
>> coded indexing.
>> 
> I thought about that after the post.  The file is too big
> to show but it is a mix of text and numbers in a columnated
> form.  The first column is text with various indenting, the
> second column is text, and the last 3 columns are numbers.
> I've seen the limitation of the hard coding but didn't know
> of another way.  My goal is to have a code that will read
> different text files of the same general format.  Thanks
> for the replies.

I'm not sure what you mean by "various indenting", and that detail 
could potentially make things more complicated. But one approach I've 
used it to read a line at a time using fgetl, use textscan to parse 
each column into strings (specifying the "Delimiter" as whatever 
separates your columns), and then storing everything in a cell. 
Afterward, I then try to convert every element of the cell into a 
number (using sscanf seems fastest), and replace the string with a 
number if the conversion is successful. That seems to be my best 
compromise between speed and flexibility.

--Arthur