15.2: fprintf() to a file
- Page ID
- 85192
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\( \newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\)
( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\id}{\mathrm{id}}\)
\( \newcommand{\Span}{\mathrm{span}}\)
\( \newcommand{\kernel}{\mathrm{null}\,}\)
\( \newcommand{\range}{\mathrm{range}\,}\)
\( \newcommand{\RealPart}{\mathrm{Re}}\)
\( \newcommand{\ImaginaryPart}{\mathrm{Im}}\)
\( \newcommand{\Argument}{\mathrm{Arg}}\)
\( \newcommand{\norm}[1]{\| #1 \|}\)
\( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\)
\( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\AA}{\unicode[.8,0]{x212B}}\)
\( \newcommand{\vectorA}[1]{\vec{#1}} % arrow\)
\( \newcommand{\vectorAt}[1]{\vec{\text{#1}}} % arrow\)
\( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vectorC}[1]{\textbf{#1}} \)
\( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)
\( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)
\( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)
\( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)
\(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)The fopen and fclose Functions
from Serhat Beyenir, 1.4.
The fopen command is used to open or create a file. The basic syntax for fopen is as follows:
fid = fopen(filename, permission)
For example, fo = fopen('output.txt', 'w'); opens or creates a new file named output.txt and sets the permission for writing. If the file already exists, it discards the existing contents.
The fclose command is used to close a file. For example, if we type in fclose(fo);, we close the file that
was created above. (It is necessary to close every file that is opened.)
.
The fprintf Function
from Serhat Beyenir, 1.4.
The fprintf function writes formatted data to the computer monitor or a file. This command can be used to
save the results of a calculation to a file. To do this,
- First we create or open an output file with fopen
- Second we issue the fprintf command
- Then we close the output file with fclose.
The simplified syntax for fprintf is as follows:
fprintf=(fid, format, variable1, variable 2, ...)
Start a .m file named AcetyleneBottleInteractiveOutput.m with these lines:
% This script computes the volume of an acetylene bottle
% user is prompted to enter
% a radius r for a hemispherical top
% a height h for a cylindrical part
clc % Clear screen
disp('This script computes the volume of an acetylene bottle:')
disp(' ') % Display blank line
r=input('Enter the radius of acetylene bottle in meters ');
h=input('Enter the height of cylindrical part of acetylene bottle in meters ');
Vol_top=(2*pi*r^3)/3; % Calculating the volume of hemispherical top [m3]
Vol_cyl=pi*r^2*h; % Calculating the volume of cylindrical bottom [m3]
Vol_total=Vol_top+Vol_cyl % Calculating the total volume of acetylene bottle [m3]
disp(' ') % Display blank line
str = ['The volume of the acetylene bottle is ', num2str(Vol_total), ' cubic meters.'];
disp(str);
Add the following lines to your .m file, in order to write to a file:
fo = fopen('output.txt', 'w');
fprintf(fo,'The radius of acetylene bottle: %g meters \n', r);
fprintf(fo,'The height of cylindrical part of acetylene bottle: %g meters \n', h);
fprintf(fo,'The volume of the acetylene bottle: %g cubic meters. \n', Vol_total);
fclose(fo);
Here, we first create the output.txt
file that will contain the following three variables r,
h
and Vol_total
. In the fo
output file, the variables are formated with %g
which automatically uses the shortest display format. You can also use %i
or %d
for integers and %e
for scientific notation. In our script above, the \n
(newline) moves the cursor to the next line.
Solution
Upon running the .m file, the output.txt file will display the following. The values will depend on the values you input.
The radius of acetylene bottle: 0.3 meters
The height of cylindrical part of acetylene bottle: 1.5 meters
The volume of the acetylene bottle: 0.480664 cubic meters.
.
By Carey A. Smith
%% Create a matrix showing the conversion of feet to inches.
feet = 0:2:10;
inches= feet*12;
matrix_feet_inches = [feet' , inches'];
% Display it on the screen, 2 methods:
%% Formatted Table with a header, method 1: for loop
fprintf('\n') % print a blank line
disp(' Feet Inches')
disp(' ----- ------')
[nrows, ncols] = size(matrix_feet_inches);
for n = 1:nrows
fprintf('%8.1f %8.2f \n', matrix_feet_inches(n,:))
end
%% Formatted Table with a header, method 2: Print the matrix with a single statement
fprintf('\n') % print a blank line
disp(' Feet Inches')
disp(' ----- ------')
fprintf('%8.1f %8.2f \n', matrix_feet_inches')
% The transpose is needed, becuz Matalb reads the data down columns
% but prints across rows.
% fprintf statment only 2 prints 2 values at a time.
% The format string is repeated until all of the data is printed.
%% Write the matrix to a file as a formatted table:
file_id1 = fopen('Formatted_Table.txt','wt')
% fopen() opens a file.
% file_id1 is the file's handle
% 'r' = read
% 'w' = write (Create the file, if it doesn't exist)
% 'a' = append to the end of the file, leaving any existing data
% 't' = text format
cnt1= fprintf(file_id1,' Feet Inches\n')
% cnt1 = the number of characters written each time.
cnt2= fprintf(file_id1,' ----- ------\n')
cnt3= fprintf(file_id1, '%8.1f %8.2f \n', feet, inches)
fclose(file_id1) % Close the file with finished writing
Solution
Add example text here.
By Carey A. Smith
Study example in the attached file fprintf_to_file_exponential_table.m
Then modify the example in these ways:
1. In parts A & B change the format strings, so that the x column is printed 1 decimal place instead of 2 and change the exp(x) column to be pprinted with 6 decimal places instead of 8.
2. In part B, write to the table a file with a name like this: 'exp_table1_YourName.txt'
- Answer
-
Add texts here. Do not delete this text first.
.