Skip to main content
Logo image

Section 5.5 Output Commands

In addition to the automatic echoing that MATLAB performs, there are two commands which display output: disp() and fprintf(). Both commands can generate output to the screen, which is displayed in the Command Window, and the fprintf() command can also be used for output to a file.

Subsection 5.5.1 disp() Command

The disp() command is used to display single variables without the variable name:
>> disp(variable)
>> disp('some string')
Each call to disp() appears on a new line, meaning there is a built-in line break \n.
Here is an example - suppose the following code is stored in a script file scores.m:
% Script file scores.m
% Assumes that test data is available in the array tests
ave = mean(tests);    %compute test average
disp('The average score was:')
disp(ave);
Here is what happens when we execute this script file, for example by typing “scores” at the command prompt:
>> scores
The average score was:
  95

Subsection 5.5.2 fprintf() Command

The fprintf() command is similar to its namesake in C and is used for formatted output - either to the screen or to a file. Note that in MATLAB there is no separate printf() command for output to the screen. Both cases - output tot the screen as well as output to a file - use the fprintf() command. Here is the syntax:
>> fprintf(fid, format string, variables)
Just like in C, the format string contains literal text, escape sequences, and format specifiers. We’ll learn details of formatted output in the next section.