%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Illustrates use of fprintf to output data to a file.  
%
% Requires use of additional built in functions:
%
%    fopen:  Opens file 
%    fclose: Closes file 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% First, open 'tfprintf.dat' for writing.
% 
%    First (string) argument to fopen specifies name of file.
%    Second (string) argument to fopen specifies type of access,
%       'w' means write.
%
%    Return value is an integer 'file descriptor' that is then
%    used in 'fprintf' calls.  If return value is < 0, then 
%    open failed (as could happen, for example, if you were trying
%    to open a file in a directory for which you do not have 
%    write access.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fid = fopen('tfprintf.dat', 'w');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Bail out if can't open file for write ...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if fid < 0 
   fprintf('Could not open ''tfprintf.dat'' for write.\n');
   return;
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Now use fprintf to output integers from 1 to 10, their squares 
% and cubes as three columns ...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 
for i = 1 : 10
   fprintf(fid,'%g %g %g\n', i, i^2, i^3);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Close file ... until the file is closed, there is no guarantee
% that what you think you've written to the file is actually 
% there! 
%
% Note that  the file descriptor, NOT the file name is the argument
% passed to fclose ...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
fclose(fid);

