| Development Environment | ![]() |
Writing Formatted Text Files
The fprintf function converts data to character strings and outputs them to the screen or a file. A format control string containing conversion specifiers and any optional text specify the output format. The conversion specifiers control the output of array elements; fprintf copies text directly.
Common conversion specifiers include:
%e for exponential notation%f for fixed point notation%g to automatically select the shorter of %e and %fOptional fields in the format specifier control the minimum field width and precision. For example, this code creates a text file containing a short table of the exponential function.
x = 0:0.1:1; y = [x; exp(x)];
The code below writes x and y into a newly created file named exptable.txt.
fid = fopen('exptable.txt','w');
fprintf(fid,'Exponential Function\n\n');
fprintf(fid,'%6.2f %12.8f\n',y);
status = fclose(fid);
The first call to fprintf outputs a title, followed by two carriage returns. The second call to fprintf outputs the table of numbers. The format control string specifies the format for each line of the table:
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);
The second line reads the file title. The third line reads the table of values, 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));
| Reading Formatted ASCII Data | Closing a File | ![]() |