Intermediate

I/O Operations in MATLAB

Learn console and file input/output in MATLAB with fprintf, disp, fopen, fgetl, and matrix I/O using Docker-ready GNU Octave examples

Input and output are how a program communicates with the outside world — the terminal, files on disk, and the user. In the Hello World tutorial you met disp for a one-line greeting. Real programs need more: formatted numbers, columns of data, reading and writing files, and loading numeric matrices back into the workspace.

Because MATLAB grew out of numerical computing, its I/O reflects that heritage. It borrows C’s printf family (fprintf, sprintf) for precise formatting, but it also ships matrix-aware helpers like dlmwrite, dlmread, save, and load that treat an entire array as a single unit. This array-first attitude means a single fprintf call can walk an entire matrix, and a single dlmread can pull a whole CSV back into a variable.

In this tutorial you’ll format output with fprintf and disp, write and read plain-text files with the fopen/fclose handle pattern, round-trip numeric matrices through CSV and MATLAB’s binary .mat format, and read interactive input with input. All examples run unmodified in GNU Octave, the free MATLAB-compatible environment used for this site’s Docker examples.

Formatted Console Output

disp is convenient but gives you no control over formatting. For precise output — decimal places, column widths, scientific notation — use fprintf, which follows the same conversion specifiers as C’s printf.

Create a file named formatted_output.m:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
% Formatted console output with fprintf and disp

% Integer and floating-point conversion specifiers
fprintf('Integer: %d\n', 42);
fprintf('Float (2 decimals): %.2f\n', pi);
fprintf('Scientific: %e\n', 12345.678);
fprintf('Padded to width 8: %8.3f\n', pi);

% Strings use %s
name = 'MATLAB';
fprintf('Language: %s\n', name);

% Multiple values are consumed left to right
fprintf('%s first appeared in %d\n', name, 1984);

% fprintf reuses the format string across a whole matrix
% (values are consumed in column-major order)
squares = [2 4 6; 4 16 36];
fprintf('%d squared is %d\n', squares);

% disp is best for quick, unformatted inspection
disp('--- disp examples ---');
disp(42);
disp([1 2 3]);

% num2str converts a number into text you can concatenate
label = ['pi = ', num2str(pi)];
disp(label);

The key trick is the matrix in the last fprintf: MATLAB stores arrays in column-major order, so [2 4 6; 4 16 36] is read as 2, 4, 4, 16, 6, 36. The format string '%d squared is %d\n' consumes two values per pass, producing the pairs (2,4), (4,16), (6,36).

Writing and Reading Text Files

File I/O in MATLAB uses a handle (called a file identifier or fid) returned by fopen. You write with fprintf, read line-by-line with fgetl, and always release the handle with fclose. The mode string — 'w' for write, 'r' for read, 'a' for append — mirrors C’s fopen.

Create a file named file_io.m:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
% Writing to and reading from a text file

% --- Writing ---
fid = fopen('greetings.txt', 'w');       % open for writing (truncates)
fprintf(fid, 'Hello from MATLAB\n');
fprintf(fid, 'Line number %d\n', 2);
fprintf(fid, 'Pi is approximately %.4f\n', pi);
fclose(fid);                             % always close the handle

disp('File written. Reading it back line by line:');

% --- Reading line by line ---
fid = fopen('greetings.txt', 'r');       % open for reading
line = fgetl(fid);                       % read the first line
while ischar(line)                       % fgetl returns -1 at end of file
    fprintf('  %s\n', line);
    line = fgetl(fid);                   % advance to the next line
end
fclose(fid);

% --- Reading the whole file at once ---
contents = fileread('greetings.txt');
fprintf('Total characters read: %d\n', length(contents));

Two reading styles appear here. fgetl (get line) returns one line at a time and yields -1 at end of file — that’s why the loop guard is ischar(line), which becomes false once fgetl stops returning text. For small files, fileread grabs the entire contents as a single character array in one call, newlines included.

Reading and Writing Numeric Data

Because MATLAB is built around matrices, it provides I/O functions that move an entire array in one step. dlmwrite/dlmread handle delimited text (like CSV), while save/load use MATLAB’s native binary .mat format to preserve variables exactly.

Create a file named matrix_io.m:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
% Reading and writing numeric matrices

% Create a 2x3 matrix
M = [1 2 3; 4 5 6];

% Write it as comma-delimited text (dlmwrite defaults to commas)
dlmwrite('matrix.csv', M);

% Read the delimited file straight back into a variable
N = dlmread('matrix.csv');

disp('Matrix read back from matrix.csv:');
disp(N);

% Confirm the data survived the round trip
fprintf('Sum of all elements: %d\n', sum(N(:)));

% save/load use MATLAB's binary .mat format and preserve variables exactly
save('workspace.mat', 'M');
clear M;                                 % remove M from the workspace
load('workspace.mat');                   % bring it back from disk
fprintf('Recovered M(2,3) = %d\n', M(2,3));

Note sum(N(:)): the colon N(:) flattens the matrix into a single column vector so sum totals every element at once — another example of MATLAB expressing a whole-array operation without a loop. dlmread returns the data as a numeric matrix ready for computation, unlike text-based reads that give you character arrays.

Reading Interactive Input

The input function prints a prompt and waits for the user to type a value. By default it evaluates the entry as a MATLAB expression (so 5 becomes the number 5); adding the 's' option reads the entry as raw text instead.

Create a file named read_input.m:

1
2
3
4
5
6
7
8
% Reading input from the user with input()

radius = input('Enter a radius: ');      % reads and evaluates a number
area = pi * radius^2;
fprintf('A circle with radius %g has area %.4f\n', radius, area);

name = input('Enter your name: ', 's');  % the 's' option reads text
fprintf('Hello, %s!\n', name);

Because this script blocks waiting for keyboard input, it is not included in the non-interactive Docker commands below. Run it interactively, or feed it input on stdin. A sample session looks like this:

Enter a radius: 5
A circle with radius 5 has area 78.5398
Enter your name: Ada
Hello, Ada!

Running with Docker

The three non-interactive scripts run cleanly in headless GNU Octave. Each writes its output files into the mounted working directory.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Pull the GNU Octave image
docker pull gnuoctave/octave:9.4.0

# Formatted console output
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system formatted_output.m

# Text file write/read
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system file_io.m

# Numeric matrix I/O
docker run --rm -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system matrix_io.m

For the interactive read_input.m, add the -i flag and pipe values in on stdin:

1
printf '5\nAda\n' | docker run --rm -i -v $(pwd):/app -w /app gnuoctave/octave:9.4.0 octave --no-gui --no-window-system read_input.m

Expected Output

Running formatted_output.m:

Integer: 42
Float (2 decimals): 3.14
Scientific: 1.234568e+04
Padded to width 8:    3.142
Language: MATLAB
MATLAB first appeared in 1984
2 squared is 4
4 squared is 16
6 squared is 36
--- disp examples ---
42
   1   2   3
pi = 3.1416

Running file_io.m:

File written. Reading it back line by line:
  Hello from MATLAB
  Line number 2
  Pi is approximately 3.1416
Total characters read: 59

Running matrix_io.m:

Matrix read back from matrix.csv:
   1   2   3
   4   5   6
Sum of all elements: 21
Recovered M(2,3) = 6

Key Concepts

  • fprintf for precision — It uses C-style conversion specifiers (%d, %.2f, %e, %8.3f, %s) and requires an explicit \n for newlines, giving you exact control over formatting.
  • Matrices flow through fprintf — A format string is reused across every element of an array, consumed in column-major order, so one call can print an entire matrix.
  • disp vs. fprintfdisp is quick and automatically appends a newline but offers no formatting; reach for fprintf when layout matters.
  • The file-handle patternfopen returns a fid, you read or write through it, and you must fclose it. Mode strings 'r', 'w', and 'a' control reading, overwriting, and appending.
  • Two reading stylesfgetl reads one line at a time and returns -1 at end of file; fileread slurps the whole file into a single character array.
  • Matrix-aware I/Odlmwrite/dlmread round-trip delimited numeric data, while save/load preserve workspace variables exactly in the binary .mat format.
  • input reads from the user — It evaluates typed entries as expressions by default; pass the 's' option to capture raw text instead.
  • Octave compatibility — All of these I/O functions behave identically in MATLAB and GNU Octave, so the same .m files run in both environments.

Running Today

All examples can be run using Docker:

docker pull gnuoctave/octave:9.4.0
Last updated:

Comments

Loading comments...

Leave a Comment

2000 characters remaining