fscanf in MATLAB

Unlike in C/C++, fscanf in MATLAB repeats the scanning as long as the formatted text matches. It is convenient but also confusing sometimes.

For example, in a text file there are lines as follows.

Image Width Height: 800, 600
Red X Y Radius: 200, 300, 300
Green X Y Radius: 300, 400, 200
Blue X Y Radius: 500, 500, 150

We can read the first line using

dim = fscanf(fid, '%*s %*s %*s %d, %d\n');             (a)

A problem arises after this scanning since it tries to scan the next line as well with the format that is given. So even if you try to read the next line with the fscanf (b), the scanning will fail since the fscanf in (a) tries to scan the next line.

redc = fscanf(fid, '%*s %*s %*s %*s %d, %d, %d\n');    (b)

So in this specific case, it is better to use the followings.

dim  = fscanf(fid, 'Image Width Height: %d, %d\n');
redc = fscanf(fid, 'Red X Y Radius: %d, %d, %d\n');
grnc = fscanf(fid, 'Green X Y Radius: %d, %d, %d\n');
bluc = fscanf(fid, 'Blue X Y Radius: %d, %d, %d\n');

There are better ways but this would be quick fix.


About Jaerock

Assistant Professor of Computer Engineering Dept. of Electrical and Computer Engineering Kettering University

Posted on April 22, 2014, in Uncategorized. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: