Chapter 9 Attaway MATLAB 4E Using MAT-files for variables MATLAB - - PowerPoint PPT Presentation

chapter 9
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Chapter 9

Attaway MATLAB 4E

Advanced File Input and Output

slide-2
SLIDE 2

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 .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

slide-3
SLIDE 3

Working with spreadsheet files

— The functions xlsread and xlswrite can be used for

Excel spreadsheet/file I/O

— 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

slide-4
SLIDE 4

File Input/Output (I/O)

— Lower-level file I/O functions are used to read from,

write to, and append to files when load and save cannot be used

— MATLAB has functions to read from and write to many

different file types, for example, spreadsheets

— MATLAB has a special binary file type that can be used

to store variables and their contents in MAT-files

slide-5
SLIDE 5

Lower Level File I/O Functions

— 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

slide-6
SLIDE 6

Opening Files

— 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

slide-7
SLIDE 7

Closing Files

— Files are closed using the fclose function — It is also possible for the fclose to fail; the function

returns 0 if the file close was successful or -1 if not

— General forms of calling it:

closeresult = fclose(fid); % File ID stored in variable fid closeresult = fclose('all'); % Closes all open files

slide-8
SLIDE 8

Generic open/close code

— 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

slide-9
SLIDE 9

File Input Functions

— fscanf reads formatted data into a matrix, converting

characters to ASCII equivalents

— textscan reads text data from a file into column

vectors stored in a cell array

— fgetl and fgets read strings from a file one line at a

time (if there is a newline character at the end of the line, fgets keeps it whereas fgetl gets rid of it)

— 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

slide-10
SLIDE 10

Using fgetl to read

— 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

slide-11
SLIDE 11

Example using fgetl

— 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

slide-12
SLIDE 12

File Output: Using fprintf

— 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

  • f bytes is not seen)

— Everything you have learned about fprintf so far applies; the only

difference is writing to a file vs. to the screen

slide-13
SLIDE 13

Example using fprintf

— The following is an example of writing to a file named

“tryit.txt” (error-checking omitted):

>> fid = fopen('tryit.txt', 'w'); >> for i = 1:3 fprintf(fid,'The loop variable is %d\n', i); end >> fclose(fid);

slide-14
SLIDE 14

Using fscanf to read

— 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

slide-15
SLIDE 15

fscanf: Format

— The format includes conversion characters

much like those used in the fprintf function; the format specifies exactly how each line in the file is formatted

— 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

number and the letter, skipping the space in between them, or the format string ‘%f%c%c’ could be used to read the number, the space, and the letter

slide-16
SLIDE 16

fscanf: Dimensions

— 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

  • matrix. The dimensions [2 inf] would be used to create a matrix that

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.

slide-17
SLIDE 17

Example using fscanf

— 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

is the ASCII equivalents of the letters

slide-18
SLIDE 18

Using textscan to read

— The textscan function also reads in the entire file at

  • nce; no loop is required

— 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 file are formatted

— the elements in the cell array will be column vectors of

the “columns” from the file

slide-19
SLIDE 19

Example using textscan

— 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

from the file; the second is the letters

slide-20
SLIDE 20

File Input Functions: Summary

— 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

slide-21
SLIDE 21

Common Pitfalls

— Misspelling a file name, which causes a file open to be

unsuccessful

— Using a lower-level file I/O function, when load or

save could be used

— Forgetting that fscanf reads columnwise into a matrix,

so every line in the file is read into a column in the resulting matrix

— Forgetting that fscanf converts characters to their

ASCII equivalents.

— Forgetting that textscan reads into a cell array (so

curly braces are necessary to index)

slide-22
SLIDE 22

Programming Style Guidelines

— Always close files that were opened. — Always check to make sure that files were opened and

closed successfully.

— Make sure that all data are read from a file; for

example, use a conditional loop to loop until the end

  • f the file is reached rather than using a for loop.

— Be careful to use the correct formatting string when

using fscanf or textscan.

— Store groups of related variables in separate MAT-files.