Chapter 9
Attaway MATLAB 4E
Advanced File Input and Output
Chapter 9 Attaway MATLAB 4E Using MAT-files for variables MATLAB - - PowerPoint PPT Presentation
Advanced File Input and Output Chapter 9 Attaway MATLAB 4E Using MAT-files for variables MATLAB has functions that allow reading and saving variables from files These files are called MAT-files (because the extension on the file name is
Attaway MATLAB 4E
Advanced File Input and Output
MATLAB has functions that allow reading and saving variables from
files
These files are called MAT-files (because the extension on the file name
is .mat)
Variables can be written to MAT-files, appended to them, and read
from them
Rather than just storing data, MAT-files store variable names and their
values
To save all workspace variables in a file, the command is:
save filename
To save just one variable to a file, the format is:
save filename variablename
To append:
save -append filename variablename
To read variables from a MAT-file into the base workspace:
load filename variable list
The functions xlsread and xlswrite can be used for
General forms to write from/read into a matrix:
xlswrite('filename',matrixvariable) matrixvariable = xlsread('filename')
Can read from files with extension .xls, .xlsx, etc. For more complicated spreadsheets:
[nums, txt] = xlsread(filename')
this will read the numbers into a matrix variable nums
and the rest into a cell array txt
Lower-level file I/O functions are used to read from,
MATLAB has functions to read from and write to many
MATLAB has a special binary file type that can be used
If a file has the same number of values on every line, and the
same type, load can be used to read from the file into a matrix
Similarly, save can be used to write or append a matrix to a file If what you have is not so regular – e.g., combinations of
numbers and character strings – lower level file input/output functions must be used
To use these functions, the file must be opened first, and closed
when the operation on the file has been completed. The algorithm is:
open the file read from the file, write to it, or append to it close the file
Files have to be opened using the fopen function, which
specifies the name of the file and the mode (reading/writing/appending)
If the fopen function is able to locate and open the file, it
returns a file identifier number, which is then saved in a variable and becomes the method of referring to the file
General form:
fid = fopen('filename', 'permission string');
where the permission string is r (default), w, or a it is possible that the fopen could fail if the file doesnt exist (in
which case it returns -1), so that should be checked
Files are closed using the fclose function It is also possible for the fclose to fail; the function
General forms of calling it:
closeresult = fclose(fid); % File ID stored in variable fid closeresult = fclose('all'); % Closes all open files
The generic code to open the file/use it/close the file is:
fid = fopen('filename'); % Assumes opening for reading if fid == -1 disp('File open not successful') else % Use the file! closeresult = fclose(fid); if closeresult == 0 disp('File close successful') else disp('File close not successful') end end
fscanf reads formatted data into a matrix, converting
textscan reads text data from a file into column
fgetl and fgets read strings from a file one line at a
Since only one line is read at a time, these are put in a
while loop that reads until the end of the file is reached
The function fgetl reads the next line from a file as a string String functions are used to manipulate the data Since fgetl only reads one line, it is placed in a loop that keeps
going until the end of the file is reached.
The function call feof(fid) would return logical true if the end of
the file has been reached for the file identified by fid, or logical false if not
General form:
while feof(fid) == 0 % OR: while ~feof(fid) aline = fgetl(fid); % Use string functions to extract numbers, strings, etc. % Do something with the data! end
If the file has the following format:
5.3 a 2.2 b
this code will read and echo print the data:
while feof(fid) == 0 aline = fgetl(fid); % Separate each line into the number and character % code and convert to a number before printing [num, charcode] = strtok(aline); fprintf('%.2f %s\n', str2double(num), charcode) end
If you have a matrix, save can be used to write it to a file Otherwise, the lower-level output function must be used, fprintf To use fprintf, the file must be opened first, and closed when the
writing has been completed (use w with the fopen for writing to the file, a for appending)
The general form is:
fprintf(fid, 'format', variable(s));
The fprintf function actually returns the number of bytes that was
written to the file, so if it is not desired to see that number, the output should be suppressed with a semicolon as shown
(Without a file identifier, the output goes to the screen and the number
Everything you have learned about fprintf so far applies; the only
difference is writing to a file vs. to the screen
The following is an example of writing to a file named
>> fid = fopen('tryit.txt', 'w'); >> for i = 1:3 fprintf(fid,'The loop variable is %d\n', i); end >> fclose(fid);
The format of using the fscanf function is:
mat = fscanf(fid, 'format', [dimensions])
The fscanf function reads from a file identified by fid
directly into the matrix variable mat column-wise (In other words, every line in the file becomes a column in the matrix) – no loop required!
If the file contains both numbers and characters, the
characters will be converted to their ASCII equivalents
The matrix must be manipulated somewhat to get it back
into the original form from the file
The formatspecifies exactly how each line in the file is
formatted
The dimensions specify the desired dimensions of mat
For example, if the file has the following format:
5.3 a 2.2 b
The format string ‘%f %c’ could be used to read the
The dimensions specify the desired dimensions of the matrix; if the
number of values in the file is not known, inf can be used for the second dimension
Every line in the file is read into a column in the matrix For example, if the file has the following format:
5.3 a 2.2 b 3.3 a
and the format string ‘%f %c’ is used, this specifies that two values will
be read from every line so there will be two rows in the resulting
has two rows by c columns, where c is the number of lines in the file. The use of the constant inf enables any number of lines from the file.
For example, if the file has the following format:
5.3 a 2.2 b 3.3 a
this will read into the matrix:
>> mat = fscanf(fid,'%f %c',[2, inf])
mat = 5.3000 2.2000 3.3000 97.0000 98.0000 97.0000
The first row is the numbers from the file; the second
The textscan function also reads in the entire file at
textscan reads into column vectors in a cell array General form:
cellarray = textscan(fid, 'format');
the format string specifies exactly how the columns in
the elements in the cell array will be column vectors of
For example, if the file has the following format:
5.3 a 2.2 b 3.3 a
this will read into the cell array:
>> subjdata = textscan(fid,'%f %c’)
subjdata = [3x1 double] [3x1 char]
The first column vector in the cell array is the numbers
Four methods of reading from a file: load works only if the file has a regular format like a matrix
(same type, same number on every line in the file)
If not, lower-level functions must be used. To use these, the file
must be opened and then closed
The fscanf function will read into a matrix, converting the
characters to their ASCII equivalents
The textscan function will instead read into a cell array that stores
each column from the file into separate column vectors of the cell array
The fgetl function can be used in a loop to read each line from the
file as a separate string; string manipulating functions must then be used to break the string into pieces and convert to numbers
The format of the lines/“columns” from the file has to be
specified for fscanf and textscan, so the format has to be consistent in the file to be able to use these functions
Misspelling a file name, which causes a file open to be
Using a lower-level file I/O function, when load or
Forgetting that fscanf reads columnwise into a matrix,
Forgetting that fscanf converts characters to their
Forgetting that textscan reads into a cell array (so
Always close files that were opened. Always check to make sure that files were opened and
Make sure that all data are read from a file; for
Be careful to use the correct formatting string when
Store groups of related variables in separate MAT-files.