Missing something obvious? (fscanf)

5 views (last 30 days)
Ian Barker
Ian Barker on 21 Mar 2013
Trying to use fscanf to read data from a file that is 24 rows by 5 columns. I've set up this:
[fileId,errorMsg] = fopen('Data.txt', 'r');
if fileId < 0
disp(errorMsg);
else
NUMROWS = 24;
for row = 1:NUMROWS
for col = 1:5
data(row,col) = fscanf(fileId, '%d', inf);
end
end
end
but I keep getting a "Subscripted assignment dimension mismatch." error when I run it. Not sure if I'm missing some obvious error or if I'm just doing this wrong to begin with.
Thanks very much for your help in advance.
  4 Comments
Image Analyst
Image Analyst on 21 Mar 2013
Is the file text, or binary?
Ian Barker
Ian Barker on 21 Mar 2013
Just a standard text file.

Sign in to comment.

Accepted Answer

Cedric
Cedric on 21 Mar 2013
Edited: Cedric on 21 Mar 2013
If you need to stick to FSCANF, you can do
fid = fopen('Data.txt', 'r') ;
data = fscanf(fid, '%f', [24, 5])
fclose(fid) ;
  4 Comments
Ian Barker
Ian Barker on 21 Mar 2013
Edited: Ian Barker on 21 Mar 2013
What I meant to say was that I get the correct array with the correct size and numbers but in a very wrong order. The data is supposed to be organized with each category of information being in one column, but after using fscanf it seems to read and order it in some weird way.
For example I want to get this as the top row:
1 0.032 +170 1.5 -16.0
but instead i get this:
1 13.4000 9.5000 500 1.7000
Ian Barker
Ian Barker on 21 Mar 2013
Aha I think i got it. Just had to change the %d in my earlier code to a %f and it magically works now.
Thanks alot for your help anyways.

Sign in to comment.

More Answers (1)

Image Analyst
Image Analyst on 21 Mar 2013
You can only assign one value to data(row,col) so why do you have inf instead of 1? Anyway, why don't you just use fread() to read the whole stream of data into a 2D array directly? Why use fscanf()?
  1 Comment
Ian Barker
Ian Barker on 21 Mar 2013
I'd love to use the many other easier ways of reading this file. But unfortunately I am being forced to use fscanf for some reason.

Sign in to comment.

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!