Matlab IO

From Sutherland_wiki
Jump to: navigation, search

Output in MATLAB

Output in Matlab can be accomplished in several ways. Here we briefly summarize the various output options, which are discussed in more detail below.

  • disp - The disp command is the simplest way to dump information to the command window, but does not allow control over formatting, and cannot be used for file output.
  • fprintf - The fprintf command allows much more control over output, and can be used to dump results to the command window or to files.
  • save - The save command can be used to save variables to disk. The load command can then be used to load them back from disk.

Basic output using DISP

The disp command is the simplest output command. It can be used to output variable contents or text strings:

  T = linspace(50,250,5);
  disp('the temperatures (C) are:');
  disp( T );

Formatted output using FPRINTF

The fprintf command provides significantly more control over output. The basic usage of this command is:

  fprintf( 'formatting & text', v1, v2, ... vn );       % print to command window
  fprintf( fid, 'formatting & text', v1, v2, ... vn );  % print to a file

This prints several variables, interspersed with text, to a file with the identifier fid. If no file id is specified, the output goes to the screen. The formatting is controlled by the formatting string.

Controlling Formatting

Output is formatted using a string in the form %a.bc, where:

  • a represents the minimum width to use for the output. Note that if you don't want a minimum set, you can always use 0 here.
  • b indicates how many digits past the decimal point to use.
  • c indicates the formatting scheme. While there are many schemes, the most common are:
    • f - floating point format such as 123.45.
    • e - scientific notation format such as 1.2345e2.
    • g - Matlab chooses the "best" between scientific and floating point.
    • s - string format (used to print out text).

Occassionally we simplify this to %ac or %c, both of which are also valid.

Here are some examples:

Matlab Code Output
theta = pi/3;   % define the angle.

% Print the cos of the angle to the command window.
% Format using a floating point number with
% 3 decimal places.
fprintf('cos(%0.3f) = %0.3f\n', theta, cos(theta));

% print out the same information in a different form.
% Here we use scientific notation with three
% significant figures.
fprintf('The cos of %0.2e is %0.2e\n',theta,cos(theta));

fprintf('cos(%f) = %f\n',theta,cos(theta));
cos(1.047) = 0.500
The cos of 1.05e+00 is 5.00e-01
cos(1.047198) = 0.500000
% print a table of angles and cos, sin of those angles.
% Each column in the table is 12 spaces wide.
npts = 10;
theta = linspace(0,180,npts) * pi/180;

% print the column headers.
fprintf('%12s %12s %12s %12s\n\n','theta (rad)',...
        'theta (deg)','cos(theta)','sin(theta)');

% print the data with three decimal places, and use
% fields that are 12 spaces wide.  Put a new line
% after each row.
for i=1:npts
  fprintf('%12.3f %12.3f %12.3f %12.3f\n',theta(i),...
 theta (rad)  theta (deg)   cos(theta)   sin(theta)

       0.000        0.000        1.000        0.000
       0.349       20.000        0.940        0.342
       0.698       40.000        0.766        0.643
       1.047       60.000        0.500        0.866
       1.396       80.000        0.174        0.985
       1.745      100.000       -0.174        0.985
       2.094      120.000       -0.500        0.866
       2.443      140.000       -0.766        0.643
       2.793      160.000       -0.940        0.342
       3.142      180.000       -1.000        0.000
year = [ 1750 1800 1850 1900 1950 2005 ];
pop = [ 791000 978000 1262000 165000 2518629 6453628 ];
for i=1:length(year)
  fprintf('The world population in %1.0f was %1.2e\n',year(i),pop(i) );

Data used in this example is from [1]

The world population in 1750 was 7.91e+05
The world population in 1800 was 9.78e+05
The world population in 1850 was 1.26e+06
The world population in 1900 was 1.65e+05
The world population in 1950 was 2.52e+06
The world population in 2005 was 6.45e+06
names = {'Bob','Jill','Carl','Steve'};
for i=1:length(names)

In the above examples, you may have noticed that we used \n. This is a control character that produces a carriage return (new line). There are many control characters, summarized in the following table:

Control Characters for Output Formatting
Control Code Description Matlab Example Output
\n New Line
\t A Tab character (useful for spacing)
fprintf('\tline 1\nline 2\n');
	line 1
line 2
\\ Inserts a backslash
fprintf('backslash: \\');
fprintf(' backslash: \\\nthen a new line\n');
backslash: \ A backslash: \
and then a new line
′′ Inserts a single quote
a = pi;
fprintf('The value of ''a'' is %1.3f\n',a);
The value of 'a' is 3.142
%% Inserts a % sign
score = 0.75;
fprintf('Your score is %2.0f%%\n',100*score);
Your score is 75%

Left Justifying Output

Be default, output is right-justified. To left-justify the output, insert a "-" sign between the % and the formatting string. For example,

Matlab Code Output
fprintf('There were %10.1e people in %4.0f\n',2518629,1950);

Here the field width for the number of people is 10. The number width is less than that, so the output will be right-justified.

There were    2.5e+06 people in 1950
fprintf('There were %-10.1e people in %4.0f\n',2518629,1950);
There were 2.5e+06    people in 1950
fprintf('%10s %10s\n','pi','sin(pi)');      % right justified
fprintf('%10.5f %10.5f\n',pi,sin(pi))       % right justified
        pi    sin(pi)
   3.14159    0.00000
fprintf('\n%-10s %-10s\n','pi','sin(pi)');  % left justified
fprintf('%-10.5f %-10.5f\n',pi,sin(pi));    % left justified
pi         sin(pi)   
3.14159    0.00000   

File Output

The fprintf command may be used to write formatted output to files. This requires three steps:

  1. Open the file for writing. Use the fopen command to open files.
  2. Write to the file using the fprintf command.
  3. Close the file using the fclose command.

Here is an example of writing data to a file.

Matlab Code Contents of "myOutput.dat"
x = linspace(-pi,pi);
y = sin(x);

% step 1: open the file
out = fopen('myOutput.dat');

% step 2: write data to the file
fprintf(out,'%-10s %-10s\n','x','sin(x)');
for i=1:length(x)
  fprintf(out,'%-10.5f %10.5f\n',x(i),y(i));

% step 3: close the file
x          sin(x)    
-3.14159     -0.00000
-2.44346     -0.64279
-1.74533     -0.98481
-1.04720     -0.86603
-0.34907     -0.34202
0.34907       0.34202
1.04720       0.86603
1.74533       0.98481
2.44346       0.64279
3.14159       0.00000

Note that the file "myOutput.dat" will be saved in the directory where the script was run from.

Saving Variables with SAVE

The save command may be used to save any variables defined in Matlab to a file. You can then load this file back into Matlab and your variables will be defined. The basic syntax is:

  save FILENAME;         % save ALL variables to a file called "FILENAME.mat"
  save FILENAME x1 x2 y; % save only x1 x2 and y to "FILENAME.mat"

To load the file, use

  load FILENAME;

For example:

a = rand(3);
b = 1:5:100;
c = {'Bob','Fred','Kerry','Jill'};
save myVars;      % save all variables to the file "myVars.dat"

clear;            % now no variables are defined.
load myVars;      % loads the file myVariables.mat
who;              % a, b, and c are defined again.

save myVars b c;  % save only b and c.
clear;            % now no variables are defined.
load myVars;
who;              % b and c are defined.  a is not.

Input in MATLAB

Input can be accomplished in several ways in Matlab:

  • Interactive input from the user. This is accomplished using the input command.
  • Reading files from disk. There are two common methods to do this: using fscanf command and using the load command.

The INPUT command

The basic syntax for the input command is:

x = input('text to command window');

This outputs the given text to the command window. The user can then enter a value and it will be stored in x.

The FSCANF command

There are three steps to read from a file:

  1. Open the file using fopen
  2. Read from the file using fscanf
  3. Close the file using fclose

The fscanf command is used primarily for reading from files. The basic syntax is:

value = fscanf( fid, format, size );
fid The identifier for the file to read from. This is obtained using the fopen command.
format A text string indicating the format to use when reading values from the file. This is of the form %Na, where N specifies the width to read and f specifies the format to read.
%c Reads a character (e.g. "q")
%s Reads a character string (e.g. "quiet")
%d Reads an integer (e.g. 12345)
%f Reads a floating point number (e.g. 5.62)
size OPTIONAL - sets a maximum limit on the number of entries to be read from the file. If omitted, then all of the file may be read. Valid specifications are:
  • N - read at most N entries from the file.
  • inf - read at most to the end of the file.
  • [M,N] - read M*N entries from the file and arrange them into an M x N matrix.

Opening and Closing Files

Before reading from a file, we must open it. This is done using the fopen command:

fid = fopen('filename','r');  % opens a file named "filename" for reading.

This assigns an identifier to fid that can be used in subsequent file operations (reading, closing, etc.). The 'r' indicates that this file is to be read from. Options are:

Flags for fopen
Flag Description
'r' Open a file for reading.
'w' Open a file for writing (creates the file if it doesn't already exist). An existing file will be overwritten.
'a' Open a file and append it (creates the file if it doesn't already exist).

After you are done with a file, you should close it using the fclose command:

fclose(fid);  % closes the file referred to be "fid"

A Simple Example

File "ages.dat" Matlab Commands Explanation
Fred 64
Bob   32
Julia  49
file = fopen('ages.dat','r');
name = fscanf( file, '%s', 1 );
age  = fscanf( file, '%s' );
Reads a string number into the variable name. Note the "1" at the end of this statement. If we didn't use "1" when reading the name, then it would have read the entire file into the string. After reading the name, we read the age into the variable age.

If we wanted to read the whole file, we would need a few additional things:

  • A cell array to hold the names
  • An array to hold the ages.
  • A way to determine when we hit the end of the file. This is done using the feof(fid) command.

Using these concepts, we can now read the file.

fid = fopen('ages.dat','r');      % opens the file "ages.dat" for reading.
i = 1;
names = {};
ages = [];
while ~feof(fid)
  names{i} = fscanf(fid,'%s',1);  % read the name.
  age(i)   = fscanf(fid,'%i');    % read the age.
  i = i+1;                        % get ready to read the next line
fclose(fid);                      % close the file.