Subsection Printing Results with fprintf
Scripts often need to communicate results to a user. The simplest way to do this is to type a variable name or use
disp. For more polished output, use the fprintf command.
The
fprintf command is a very useful tool for sending messages to the Command Window from your program. The general pattern is:
fprintf('text with placeholders', value1, value2, ...);
The βplaceholdersβ start with a percent sign and indicate how MATLAB should display each value. Here are the most common ones:
-
%ifor integers (whole numbers) -
%ffor decimal (fixed-point) numbers -
%gfor a compact numeric format (often a good default) -
%sfor text
You can control rounding by specifying the number of digits after the decimal point. For example,
%.2f prints two digits after the decimal.
r = 4.5;
C = 2*pi*r;
A = pi*r^2;
fprintf('Radius r = %.2f\n', r);
fprintf('Circumference C = %.3f\n', C);
fprintf('Area A = %.3f\n', A);
Two special characters are especially common in formatted output:
-
\nstarts a new line -
\tinserts a tab
x = 12;
y = 3.4567;
fprintf('x:\t%d\n', x);
fprintf('y:\t%.2f\n', y);
You can also control spacing with a field width. For example,
%8.2f uses a field that is 8 characters wide. This helps align columns.
a = 2;
b = -4;
c = -6;
fprintf('Coefficients:\n');
fprintf('%8s %8s %8s\n', 'a', 'b', 'c');
fprintf('%8d %8d %8d\n', a, b, c);
To print a percent sign, use
%%.
p = 0.237;
fprintf('Success rate: %.1f%%\n', 100*p);
The activities below use
fprintf. Before moving on, paste these examples into MATLAB to become more familiar with the command.
