Missing something obvious? (fscanf)

11 ビュー (過去 30 日間)
Ian Barker
Ian Barker 2013 年 3 月 21 日
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 件のコメント
Image Analyst
Image Analyst 2013 年 3 月 21 日
Is the file text, or binary?
Ian Barker
Ian Barker 2013 年 3 月 21 日
Just a standard text file.

サインインしてコメントする。

採用された回答

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 Center および File ExchangeMatrix Indexing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by