100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Programming

Reading and Writing Data Files

Learn MATLAB's core file I/O functions for reading and writing text, CSV, and binary data, including readmatrix, writematrix, and low-level fopen/fprintf.

Plotting & DataIntermediate10 min readJul 10, 2026
Analogies

Reading Delimited Text and CSV Files

readmatrix(filename) is the modern, recommended way (since R2019a) to import numeric data from delimited text files such as CSV, automatically detecting the delimiter and skipping header rows if it can identify them as non-numeric. It replaces the older csvread and dlmread functions, which are now considered not recommended because they require fixed row/column offsets and cannot handle mixed data types or missing values gracefully. For files with a mix of text and numeric columns, readtable(filename) is preferred over readmatrix because it preserves column headers as variable names and infers appropriate data types per column, returning a table object rather than a plain numeric array.

🏏

Cricket analogy: readmatrix auto-detecting delimiters and skipping headers is like a scorer's app auto-parsing a raw ball-by-ball CSV feed from a stadium sensor without needing to manually specify which row the header sits on.

matlab
% Reading numeric-only CSV data
M = readmatrix('sensor_readings.csv');

% Reading mixed-type tabular data with headers
T = readtable('experiment_results.csv');
disp(T.Properties.VariableNames);

% Writing back to disk
writematrix(M, 'processed_readings.csv');
writetable(T, 'summary_results.csv');

Low-Level Text I/O with fopen, fprintf, and fscanf

For custom text formats that readtable/readmatrix cannot parse directly, low-level functions give full control: fid = fopen(filename, 'r') opens a file and returns a file identifier, textscan(fid, formatSpec) reads data according to a format string like '%s %f %f', and fclose(fid) must be called afterward to release the file handle. Writing follows the mirror pattern: fid = fopen(filename, 'w') opens for writing (or 'a' to append), fprintf(fid, '%s,%.2f\n', name, value) writes formatted lines, and fclose(fid) closes the file. Forgetting fclose is a common bug — MATLAB allows a limited number of simultaneously open file identifiers, and leaving files open across many script runs can exhaust that limit or leave file handles locked on Windows.

🏏

Cricket analogy: fopen returning a file identifier that must later be closed with fclose is like a scorer's ledger being checked out from the pavilion office; forgetting to return it means the next scorer can't access the book.

Saving and Loading MATLAB Binary Data

For preserving MATLAB workspace variables exactly, including structs, cell arrays, and tables, save('data.mat', 'varname1', 'varname2') writes a binary .mat file, and load('data.mat') restores those variables into the workspace with their original names and types intact — something CSV or text export cannot do since it would flatten complex data types. save('data.mat', '-v7.3') forces the newer HDF5-based .mat format, required when saving variables larger than 2 GB or when you need partial loading of large arrays. Using matfile('data.mat') creates a handle for reading or writing chunks of a large .mat file without loading the entire file into memory, which is essential when working with datasets too large to fit in RAM.

🏏

Cricket analogy: save() preserving a struct's exact type is like archiving an entire match scorecard as a structured database record rather than flattening it into a plain text summary that loses field structure.

readtable() and writetable() round-trip cleanly for tabular data with headers, while readmatrix()/writematrix() are best for pure numeric arrays without column names — choose based on whether your data has meaningful column labels.

Always pair fopen with fclose, ideally using a try/catch or fclose('all') as a safety net in scripts, since an error thrown between fopen and fclose leaves the file handle open and can cause file-locking issues on subsequent runs.

  • readmatrix/writematrix handle pure numeric delimited files; readtable/writetable handle mixed-type tabular data with headers.
  • csvread and dlmread are legacy functions superseded by readmatrix.
  • Low-level fopen/textscan/fprintf/fclose give full control over custom text formats.
  • Always close file identifiers with fclose to avoid exhausting open-file limits.
  • save/load preserve exact MATLAB variable types (structs, cells, tables) in binary .mat files.
  • save(..., '-v7.3') is required for variables over 2 GB and enables HDF5-based partial access.
  • matfile() allows reading/writing chunks of large .mat files without loading everything into memory.

Practice what you learned

Was this page helpful?

Topics covered

#Programming#MATLABStudyNotes#ReadingAndWritingDataFiles#Reading#Writing#Data#Files#StudyNotes#SkillVeris#ExamPrep