MATLAB Programming

MATLAB Programming MATLAB Programming

cda.psych.uiuc.edu
from cda.psych.uiuc.edu More from this publisher
23.06.2015 Views

6 Data Import and Export • Two spaces • A fixed-point value of twelve characters with eight decimal places fprintf converts the elements of array y in column order. The function uses the format string repeatedly until it converts all the array elements. Now use fscanf to read the exponential data file: fid = fopen('exptable.txt','r'); title = fgetl(fid); [table,count] = fscanf(fid,'%f %f',[2 11]); table = table'; status = fclose(fid); Thesecondlinereadsthefiletitle. Thethirdlinereadsthetableofvalues, two floating-point values on each line, until it reaches end of file. count returns the number of values matched. A function related to fprintf, sprintf, outputs its results to a string instead of a file or the screen. For example, root2 = sprintf('The square root of %f is %10.8e.\n',2,sqrt(2)); Closing a File When you finish reading or writing, use fclose to close the file. For example, this line closes the file associated with file identifier fid: status = fclose(fid); This line closes all open files: status = fclose('all'); Both forms return 0 if the file or files were successfully closed or -1 if the attempt was unsuccessful. MATLAB automatically closes all open files when you exit from MATLAB. It is still good practice, however, to close a file explicitly with fclose when you are finished using it. Not doing so can unnecessarily drain system resources. 6-114

Using Low-Level File I/O Functions Note Closing a file does not clear the file identifier variable fid. However, subsequent attempts to access a file through this file identifier variable will not work. 6-115

Using Low-Level File I/O Functions<br />

Note Closing a file does not clear the file identifier variable fid. However,<br />

subsequent attempts to access a file through this file identifier variable will<br />

not work.<br />

6-115

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!