Missing something obvious? (fscanf)

9 次查看(过去 30 天)
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 个评论

请先登录,再进行评论。

采纳的回答

Cedric
Cedric 2013-3-21
编辑:Cedric 2013-3-21
If you need to stick to FSCANF, you can do
fid = fopen('Data.txt', 'r') ;
data = fscanf(fid, '%f', [24, 5])
fclose(fid) ;
  4 个评论
Ian Barker
Ian Barker 2013-3-21
编辑:Ian Barker 2013-3-21
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 2013-3-21
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.

请先登录,再进行评论。

更多回答(1 个)

Image Analyst
Image Analyst 2013-3-21
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 个评论
Ian Barker
Ian Barker 2013-3-21
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by