23.06.2015 Views

MATLAB Programming

MATLAB Programming

MATLAB Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

6 Data Import and Export<br />

• Two spaces<br />

• A fixed-point value of twelve characters with eight decimal places<br />

fprintf converts the elements of array y in column order. The function uses<br />

the format string repeatedly until it converts all the array elements.<br />

Now use fscanf to read the exponential data file:<br />

fid = fopen('exptable.txt','r');<br />

title = fgetl(fid);<br />

[table,count] = fscanf(fid,'%f %f',[2 11]);<br />

table = table';<br />

status = fclose(fid);<br />

Thesecondlinereadsthefiletitle. Thethirdlinereadsthetableofvalues,<br />

two floating-point values on each line, until it reaches end of file. count<br />

returns the number of values matched.<br />

A function related to fprintf, sprintf, outputs its results to a string instead<br />

of a file or the screen. For example,<br />

root2 = sprintf('The square root of %f is %10.8e.\n',2,sqrt(2));<br />

Closing a File<br />

When you finish reading or writing, use fclose to close the file. For example,<br />

this line closes the file associated with file identifier fid:<br />

status = fclose(fid);<br />

This line closes all open files:<br />

status = fclose('all');<br />

Both forms return 0 if the file or files were successfully closed or -1 if the<br />

attempt was unsuccessful.<br />

<strong>MATLAB</strong> automatically closes all open files when you exit from <strong>MATLAB</strong>. It<br />

is still good practice, however, to close a file explicitly with fclose when you<br />

are finished using it. Not doing so can unnecessarily drain system resources.<br />

6-114

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

Saved successfully!

Ooh no, something went wrong!