Textscan - reading data into Cell Array

I have a time stamped text file that looks like this
1 1 POSITION -3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
and it is repeated 10000 times with some text and blank lines in between, like shown below
2 1 POSITION -3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
asdasdsd
fasdasdasdasdasdsad
3 1 POSITION -3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
4 1 POSITION -3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
I am using the following textscan statement to read the data above
pos= textscan(fid, '%f%f%s%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f', 1, 'headerLines', 1)
Can anyone tell me how to read one line of data using textscan and then ignore couple of lines after that and then using textscan again to read another line and then append to the existing cell array?
Thanks in advance,
Sridhar

Answers (2)

To read a line, use Line=fgetl(fid). textscan works on string Line too.

4 Comments

I need to parse the text input into different fields ( cant do it using fgetl...very slow)
Those irregular text, do they have particular patterns? Can you utilize the 'CommentStyle' parameter of textscan()?
Also, why use %10.3f instead of %f?
Line='1 1 POSITION -3.4310 2.9600 2.0200 0.3250 0.2440 0.2300';
pos= textscan(Line, '%f%f%s%10.3f%10.3f%10.3f%10.3f%10.3f%10.3f') doesn't give correct result but
pos= textscan(Line, '%f%f%s%f%f%f%f%f%f') does.
changing 10.3%f to %f improved performance by 1.0 sec for each cycle, thats good.
the irregular text has no format, so cant use CommentStyle..
thanks!

Sign in to comment.

Depending on your MATLAB version, you may try importdata(). In r2007b, it worked out well.
>> a=importdata('test.txt')
a =
data: [4x6 double]
textdata: {4x3 cell}
>> a.data
ans =
-3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
-3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
-3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
-3.4310 2.9600 2.0200 0.3250 0.2440 0.2300
>> a.textdata
ans =
'1' '1' 'POSITION'
'2' '1' 'POSITION'
[1x36 char] '1' 'POSITION'
'4' '1' 'POSITION'
>> b=a.textdata
b =
'1' '1' 'POSITION'
'2' '1' 'POSITION'
[1x36 char] '1' 'POSITION'
'4' '1' 'POSITION'
>> b{3,1}
ans =
asdasdsd
fasdasdasdasdasdsad
3

Asked:

on 1 Jul 2011

Community Treasure Hunt

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

Start Hunting!