TExcelTAD
Home › MATLAB / Octave › Displaying Output

Displaying Output

There are three ways to show a value: leave off the semicolon, call disp, or format it precisely with fprintf / sprintf. Each has its place.

Leaving off the semicolon

The quickest way to look at a variable is to type its name or end the assignment without ;. The output includes the variable's name, which is great while exploring but noisy in a finished script.

matlab · try it yourself
speed = 88
speed
speed = 88
speed = 88

disp

disp(x) prints the value only, without the name, followed by a newline. It works for numbers, arrays and text:

matlab · try it yourself
disp(88)
disp([1.5 2.5 3.5])
disp('Engine started')
disp(['Speed: ' num2str(88) ' km/h'])
88
   1.5000   2.5000   3.5000
Engine started
Speed: 88 km/h

The last line builds one char array by joining three pieces with square brackets. num2str converts the number to text first, because you can't concatenate a number directly into a char array (MATLAB would treat 88 as a character code).

fprintf: formatted printing

fprintf(format, values...) prints text with placeholders replaced by values, in the style of C's printf. It does not add a newline automatically; you write \n yourself.

matlab · try it yourself
item = 'Coffee';
price = 3.5;
qty = 4;
fprintf('%s x %d = %.2f EUR\n', item, qty, price * qty);
fprintf('[%8.3f]\n', pi);
fprintf('[%-8.3f]\n', pi);
fprintf('[%08.3f]\n', pi);
fprintf('%e | %g | %g\n', 12345.678, 12345.678, 0.0001);
fprintf('100%% done\n');
Coffee x 4 = 14.00 EUR
[   3.142]
[3.142   ]
[0003.142]
1.234568e+04 | 12345.7 | 0.0001
100% done

Format specifiers

Specifier Meaning Example output
%d / %i Integer 42
%f Fixed point (6 decimals by default) 3.141593
%.2f Fixed point, 2 decimals 3.14
%e Exponential notation 3.141593e+00
%g Shorter of %f / %e 3.14159
%s Text hello
%c Single character h
%x Hexadecimal ff
%% A literal percent sign %

A number between % and the letter sets the minimum width (%8.3f pads to 8 characters), - left-aligns, and 0 pads with zeros. Escape sequences: \n newline, \t tab, \\ backslash, and '' (two single quotes) for an apostrophe inside a char array.

Note: Use %d only with whole numbers. If the value has a fractional part, MATLAB switches to exponential notation (3.500000e+00) while Octave prints 3.5, so the output would differ.

fprintf recycles the format

When you pass an array, fprintf reuses the format string until all the values are consumed. That makes printing a table one line of code. Values are taken in column order, so to print rows of a matrix you pass its transpose:

matlab · try it yourself
x = 1:4;
fprintf('%d squared is %d\n', [x; x.^2]);

scores = [90 85; 72 64; 88 91];      % one row per student
fprintf('Test 1: %3d   Test 2: %3d\n', scores');
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
Test 1:  90   Test 2:  85
Test 1:  72   Test 2:  64
Test 1:  88   Test 2:  91

[x; x.^2] is a 2-by-4 matrix whose columns are (1,1), (2,4), (3,9), (4,16), exactly the pairs the format wants.

sprintf: format into a variable

sprintf takes the same arguments as fprintf but returns the text instead of printing it. Use it to build labels, file names or messages:

matlab · try it yourself
runId = 7;
fileName = sprintf('results_run%03d.csv', runId);
msg = sprintf('Saved %d rows to %s', 120, fileName);
disp(fileName)
disp(msg)
disp(length(msg))
results_run007.csv
Saved 120 rows to results_run007.csv
36

Which one to use?

Situation Use
Quick look while exploring no semicolon
Print a value or simple message disp
Control decimals, alignment, tables fprintf
Need the text in a variable sprintf

Test yourself

What does fprintf('%5.1f|', 2.345) print?

  1. 2.3|
  2. 2.3|
  3. 2.345|
  4. 2|

What is the difference between fprintf and sprintf?

  1. sprintf prints to the screen faster
  2. sprintf returns the formatted text instead of printing it
  3. fprintf cannot format numbers
  4. There is no difference

How many lines does fprintf('%d\n', [1 2 3]) print?

  1. 1
  2. 2
  3. 3
  4. It is an error