fscanf to read certain lines of a txt file?

26 views (last 30 days)
Willy
Willy on 29 Apr 2014
Answered: Walter Roberson on 29 Apr 2014
Hi! I'm a matlab noob working on an assignment. I'm trying to read a text file and make a matrix with the information within the text file.
9
-18 16 -10 0 0 0 0 0 0
0 0 -10 -15 -12 6 0 0 0
0 16 0 0 0 6 0 -8 0
0 0 0 0 12 0 0 8 -14
1 1 0 0 0 0 -1 0 0
0 0 0 0 -1 1 0 -8 0
0 0 0 0 0 0 -1 -1 -1
0 -1 1 0 0 -1 0 0 0
-1 0 -1 1 0 0 0 0 0
-20
0
14
-38
0
0
0
0
0
This is what I have right now.
fileid=fopen('circuit_matrix.txt','rt');
[nsize,count]=fscanf(fileid,'%d',1);
nothing=fgetl(fileid);
A_matrix = zeros(nsize, nsize);
for i=1:nsize
[A_matrix(i,:), count]=fscanf(fileid,'%g',nsize);
nothing=fgetl(fileid);
end
With that I can get a 9x9 matrix, which serves its purpose. How can I use fscan or fgetl or basically anything to read the last 9 lines of the text(starts at line 11) file so I can make another 9x1 matrix?

Answers (1)

Walter Roberson
Walter Roberson on 29 Apr 2014
There is no operation on files to permit you to position directly to a particular line.
You can position a binary file to a specific byte offset in a file without having to read anything in-between.
When you are positioned in a file, you can read files in binary form (read character, 8 bit or 16 bit or 32 bit or 64 bit words, 32 bit single precision or 64 bit double precision), and if you use fgetl() or fgets() then the I/O layer will repeatedly read bytes until it finds the end of a line.
But you cannot advance by (say) 9 lines except by having the I/O library read 9 lines.
If you do not know how many lines from the beginning you need to go, and you only know the number of lines relative to the end, then you need to read line by line and remember where each line is, until you get to end of file, after which you can refer to the record you kept of line positions to seek directly back to the appropriate place.
In your case, after you have gone through the "for i" to read the 9 lines, you are already positioned exactly where you need to be in order to read that many more lines. So just go ahead and read them without having to do any special positioning.

Community Treasure Hunt

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

Start Hunting!