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:
| |
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:
| |
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:
| |
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:
| |
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.
| |
For the interactive read_input.m, add the -i flag and pipe values in on stdin:
| |
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
fprintffor precision — It uses C-style conversion specifiers (%d,%.2f,%e,%8.3f,%s) and requires an explicit\nfor 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. dispvs.fprintf—dispis quick and automatically appends a newline but offers no formatting; reach forfprintfwhen layout matters.- The file-handle pattern —
fopenreturns afid, you read or write through it, and you mustfcloseit. Mode strings'r','w', and'a'control reading, overwriting, and appending. - Two reading styles —
fgetlreads one line at a time and returns-1at end of file;filereadslurps the whole file into a single character array. - Matrix-aware I/O —
dlmwrite/dlmreadround-trip delimited numeric data, whilesave/loadpreserve workspace variables exactly in the binary.matformat. inputreads 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
.mfiles run in both environments.
Running Today
All examples can be run using Docker:
docker pull gnuoctave/octave:9.4.0
Comments
Loading comments...
Leave a Comment