MATLAB File read Stuck on 1 Line

4 次查看(过去 30 天)
Hi,
Its been ages since I've used MATLAB and I'm having trouble remembering how to do the whole read a file line by line thing. My program reads the first line over and over again.
fileID = fopen('qfile.txt');
fileID2 = fopen('wfile.txt');
%Now we need to keep these 2 files open untill we are finished-entil EOF
while ~feof(fileID)&& ~feof(fileID2)
[q(1),q(2),q(3),q(4)] = textread('qfile.txt','%f %f %f %f ',1)
[w(1),w(2),w(3)] = textread('wfile.txt','%f %f %f',1)
end
fclose('qfile.txt');
fclose('wfile.txt');
Thanks!

采纳的回答

Walter Roberson
Walter Roberson 2011-3-9
In line with Matt's answer, but phrasing it slightly differently:
textread() is a deprecated function which is to be passed a file name and opens the file, reads it, and closes it again.
textscan() is the newer function; it is passed a file identifier from fopen() and it does not open the file itself or close it, instead reading from whatever the current location is in the file.
Your difficulty was that the textread() call always starts from the beginning of the file, so naturally you always got the same line.
  2 个评论
Connie
Connie 2011-3-9
Kind of in line with both answers-I really do not want to read the whole file at once. Even if I mapped it into a matrix-I would need a for loop to read each row 1 row at a time. This is a simulated input to a control loop-each set of values (row or line) has a lot of calculations. And then the next line is the next input to the system. Is there a way to do that with textscan?
Matt Tearle
Matt Tearle 2011-3-9
Yes: textscan(fid,'%f%f%f%f',1);

请先登录,再进行评论。

更多回答(1 个)

Matt Fig
Matt Fig 2011-3-9
Why not just use the TEXTSCAN function instead of textread? This way you avoid the loop and read the whole file in one shot. Judging from what you wrote, I made a text file called qfile.txt which has these contents:
3.2 4.3 5.6 7.8
6.5 5.4 3.4 1.2
Then, the following reproduces this array.
fileID = fopen('qfile.txt');
T = textscan(fileID,'%f','delimiter',' ');
T = reshape(T{1},4,[]).'
fclose(fileID)

类别

Help CenterFile Exchange 中查找有关 Data Import and Export 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by