Matlab has routines to read and write ASCII files. People who've use
C's file handling routines should find the methods
familiar, though even then there are surprises.
- fgetl reads a line of text from a file, discarding any newline character
(fgets keeps the newline character). For example the following code creates a file as above, then reads the first line from it.
x=magic(3)
fid=fopen('blah.dat','w');
fprintf(fid,'%d %d %d\n', x);
fclose(fid);
fid=fopen('blah.dat');
s=fgetl(fid);
The resulting string s will contain
8 3 4
You can extract the numbers from this string using sscanf; e.g. y=sscanf(s,'%d') will put the numbers into an array called y.
- fscanf can be used to extract the numbers directly from the file, combining the behaviour of fgetl and sscanf.
For example,
x=magic(3)
fid=fopen('blah.dat','w');
fprintf(fid,'%d %d %d\n', x);
fclose(fid);
fid=fopen('blah.dat');
y=fscanf(fid,'%d');
will read all the numbers in the file, creating an column vector y that can be reshaped if necessary. fscanf is rather like the inverse of fprintf, with a similarly flexible format string that is reused until the end of the file is reached. You can limit how many numbers are read.
Replacing the fscanf line above by
while(~feof(fid)) % while not at the end of the file
[b,numbersread]=fscanf(fid,'%d',3);
b
end
will read 3 elements at a time into b, producing an empty b at the 4th attempt.
- textread reads formatted data from text files. It's useful when all lines of a text file have the
same format. For example, if a file called 'children'
contains
Name=Diana Age=10 Height=1.21
Name=Tom Age=11 Height=1.25
Name=Les Age=9 Height=1.01
then
[names, ages, heights]=textread('children','Name=%s Age=%f Height=%f')
reads the names, ages and heights into the corresponding arrays. This
uses a similar format string to fscanf - %s means that
a string is expected.
For details and further examples, see