Filter löschen
Filter löschen

MATLAB File read Stuck on 1 Line

2 Ansichten (letzte 30 Tage)
Connie
Connie am 9 Mär. 2011
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!

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 9 Mär. 2011
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 Kommentare
Connie
Connie am 9 Mär. 2011
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 am 9 Mär. 2011
Yes: textscan(fid,'%f%f%f%f',1);

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Matt Fig
Matt Fig am 9 Mär. 2011
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)

Kategorien

Mehr zu Data Import and Export finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by