Input and Output Options (last updated 9/9/99)
The information in this tutorial is located in the MATLAB manual. Any page or section numbers referred to as the MATLAB Manual are from the following:
The Student Edition of MATLAB, Version 5, The MATH WORKS Inc. Prentice-Hall, 1997.
======================================================================================
This tutorial contains the following sections;
MATLAB Prompted Input - The "input" Command
Display Text or Variable Values on the Screen - The "disp" Command
Formatting output - The "fprintf" Command
Reading From and Writing to Data Files
======================================================================================
MATLAB offers a number of methods of entering or display data, both on the screen or for submission. Effective presentation of you results is an important step in any problem. This tutorial will cover input and output options other than the default settings in MATLAB.
======================================================================================
MATLAB
Prompted Input - The "input" Command
Reference: Page 31 of the MATLAB Manual.
You can have MATLAB prompt you for input at any time by using the input command. This command will display a text string, specified by you, and then wait for input. Be sure to tell the user how to enter the data, especially if it is an array.
>> time = input('Make an initial guess for the time ') % A value of 32 is entered by the user
Make an initial guess for the time 32
time =
32
Multiple values may be entered if they are put in square brackets.
>> conc = input('Make a guess for the concentrations of A and B. Enter the values as a row array in square brackets ')
Make a guess for the concentrations of A and B. Enter the values as a row array in square brackets. [0.5 0.3]
conc =
0.5000
0.3000
A semicolon at the end of the command will cause the inputted values to not be displayed.
======================================================================================
Dialog Boxes
for User Input
An effective method for to utilize user specified input is to use a dialog box. The MATLAB code consists of two sections. The first creates the box with appropriate entry labels and title, and the second where the entries are converted to a form that is usable by MATLAB. The entries initially are in a cell array and must be converted. This is done using curly brackets to access the cell contents. Numerical data, characters, and file names can all be entered in a dialog box. Inside a dialog box you can move from field to field either with the mouse or by using the tab key.
Commands used to set the number of lines in the dialog fields and to set default values in the fields are explained by typing help inputdlg.
The use of a dialog box is demonstrated in the example code below.
% Example Program for use of Dialog Boxes
% Define a title for the dialog box
box_title = 'Data Entry for Ideal Gas Law Problem';
% Define the labels for the individual entries
entries = { 'Temperature (K)', 'Pressure
(atm)', 'Function filename'};
% Create the dialog box with the inputdlg
command
z = inputdlg(entries, box_title);
% Convert the entries. Numerical data is converted
by using the curly brackets to access the cell contents, and using the
'str2num' command to convert the string to a number. To convert the
file name only use the curly brackets. Note: these are not
parenthesis.
temp = str2num(z{1});
press = str2num(z{2});
file = z{3};
% The specified function file name (whatever the
user typed in the dialog box) is assigned the name file in the previous
step. In this example this file is called to calculate the
specific volume at the specified temperature and pressure.
spec_vol = file(temp, press)
======================================================================================
It is easy to create a menu box that allows to user to select between different options. The menu box will assign a numerical value to a defined variable. The user would then use an if / else / elseif block to do the appropriate calculations.
The creation of a menu box is demonstrated in the following section of MATLAB code.
% Example of a menu box. First a title for
the box is defined. Then the labels for the individual choices are
defined.
z = menu( 'Conversion of Temperatures', 'Celcius to Fahrenheit',
'Fahrenheit to Celcius')
% If Celcius to Fahrenheit is selected a value of 1 is assigned to z. If Fahrenheit to Celcius is selected a value of 2 is assigned to z.
======================================================================================
Reference: Pages 43-44 of Etter or Section 3.3 of the MATLAB Manual.
When values are displayed integers are always displayed as integers, while the default setting for non-integer values is 4 decimal places. This is called format short.
MATLAB allows a number of other display formats to be specified by the user.
format long 14 decimal places
format short e 4 decimals with scientific notation (Usually the preferred format)
format long e 15 decimals with scientific notation
All of these options can be selected from the toolbar OPTIONS / NUMERIC FORMAT, or by typing the format command at the screen or in your program. It may be useful to change the format at different points in an m-file.
======================================================================================
Display Text or Variable Values on the Screen - The "disp" Command
Reference: Page 3-1 of the MATLAB Manual.
The "disp" command can be used to display text or the value of a variable without display the variable name. Normally the 'fprintf' command is preferred. (see the next section).
The syntax for text is: >> disp('text string')
The syntax for variables is: >> disp(variable)
Example:
>> poly_roots = [ 1.2400 2.5600 5.6400 ] % These values are just for an example
>> disp('The roots of the cubic polynomial are')
The roots of the cubic polynomial are
>> disp(poly_roots)
1.2400 2.5600 5.6400
The text and variables can be combined without any intervening lines by using a comma in between the disp commands.
>> disp('The roots of the cubic polynomial are') , disp(poly_roots)
The roots of the cubic polynomial are
1.2400 2.5600 5.6400
======================================================================================
Formatting output - The "fprintf" Command
Reference: Page 45 of Etter or page 97 of the MATLAB Manual.
The fprintf command gives you more control over
the output than the disp command. In a single command you can specify
text and matrices to be printed, the format in which to print the matrix,
and to move down a line at some point in the output. The general syntax
is:
fprintf('format statement', matrices)
Inside the format statement the %f, %e, and %g specifiers are used to show where and how the matrix values are displayed.
%f - decimal format
%e - exponential format
%g - whichever is shorter
If \n appears in the string the display skips down a line and continues. The format statement almost always ends with a \n statement to move the display down for the next command.
Examples:
Note the value of conc is printed in the location where the specifier is located.
>> conc = 1.35;
>> fprintf('The concentration is %f g/lit \n',conc)
The concentration is 1.350000 g/lit
To control the number of decimal places displayed within the %f or %e specifier. In the following example the 4.2 means allot four places for the value, 2 to the right of the decimal point.
>> fprintf('The concentration is %4.2f g/lit \n',conc)
The concentration is 1.35 g/lit
>> conc = 0.00128;
>> fprintf('The concentration is %4.2e g/lit \n',conc)
The concentration is 1.28e-003 g/lit
You can include \n multiple times including before any text is printed.
>> fprintf('\n The concentration is %4.2f g/lit \n ,conc)
The concentration is 1.35 g/lit
How you use the specifiers when printing an array depends on how you wish the array to print, either as multiple lines or all on one line.
>> conc = [1.35 2.65
5.78 ];
>> fprintf('The concentrations are %4.2f g/lit \n',conc)
The concentration is 1.35 g/lit
The concentration is 2.65 g/lit
The concentration is 5.78 g/lit
>> fprintf(' The concentration is %4.2f %4.2f %4.2f g/lit
\n',conc)
The concentration is 1.35 2.65 5.78 g/lit
Multiple variables can be printed with a single statement.
>> conc = 1.35;
>> time = 22.4;
>> fprintf('The concentration is %4.2f g/lit at %4.1f
minutes \n',conc, time)
The concentration is 1.35 g/lit at 22.4 minutes
If conc and time are arrays you could put the fprintf statement in a for loop.
>> conc = [ 1.2 3.5 4.1 ];
>> time = [ 8.2 11.5 17.9 ];
>> for n = 1:3
fprintf('The concentration is %4.2f
g/lit at %4.1f minutes \n',conc(n),time(n))
end
The concentration is 1.20 g/lit at 8.2 minutes
The concentration is 3.50 g/lit at 11.5 minutes
The concentration is 4.10 g/lit at 17.9 minutes
Alternately you could set up columns with headings.
>> fprintf('Concentration Time \n')
>> fprintf(' (g/lit) (min) \n')
>> for n = 1:3
fprintf(' %4.2f
%4.1f \n',conc(n),time(n))
end
Concentration Time
(g/lit)
(min)
1.20
8.2
3.50
11.5
4.10
17.9
======================================================================================
Reading
From and Writing to Data Files
Often we need to read from or write to an ASCII data file so that we can use another program along with MATLAB. This could be a spreadsheet, FORTRAN, or a data acquisition program.
The command to save to an ASCII file is;
>> save filename.dat variable /ascii
The filename does not require the (.dat) extension,
but it is recommended. All the data to be saved needs to be mergred into
a single array before saving. Be sure you put it in columns or rows as
desired before executing the command. To save to the floppy drive use;
>> save a:\filename.dat variable /ascii
The command to load an ASCII data file into MATLAB is;
>> load filename.dat
The information will be stored in MATLAB as a single variable with the name, filename. To load from a floppy disk use;
>> load a:\filename.dat