%% Write to Text Files Using fprintf
% This example shows how to create text files, including combinations of numeric and character data and nonrectangular files, using the low-level fprintf function.
% fprintf is based on its namesake in the ANSI® Standard C Library. However, MATLAB® uses a vectorized version of fprintf that writes data from an array with minimal control loops.
%% Open the File
% Create a sample matrix y with two rows.

x = 0:0.1:1;
y = [x; exp(x)];

%
% Open a file for writing with fopen and obtain a file identifier, fileID. By default, fopen opens a file for read-only access, so you must specify the permission to write or append, such as 'w' or 'a'.

fileID = fopen('exptable.txt','w');

%
%% Write to the File
% Write a title, followed by a blank line using the fprintf function. To move to a new line in the file, use '\n'.

fprintf(fileID, 'Exponential Function\n\n');

% Note: Some Windows® text editors, including Microsoft® Notepad, require a newline character sequence of '\r\n' instead of '\n'. However, '\n' is sufficient for Microsoft Word or WordPad.
%
% Write the values in y in column order so that two values appear in each row of the file. fprintf converts the numbers or characters in the array inputs to text according to your specifications. Specify '%f' to print floating-point numbers.

fprintf(fileID,'%f %f\n',y);

% Other common conversion specifiers include '%d' for integers or '%s' for characters. fprintf reapplies the conversion information to cycle through all values of the input arrays in column order.
%
% Close the file using fclose when you finish writing.

fclose(fileID);

%
% View the contents of the file using the type function.

type exptable.txt

%
%% Additional Formatting Options
% Optionally, include additional information in the call to fprintf to describe field width, precision, or the order of the output values. For example, specify the field width and number of digits to the right of the decimal point in the exponential table.

fileID = fopen('exptable_new.txt', 'w');

fprintf(fileID,'Exponential Function\n\n');
fprintf(fileID,'%6.2f %12.8f\n', y);

fclose(fileID);

%
% View the contents of the file.

type exptable_new.txt

% Copyright 2012 The MathWorks, Inc.