Read .mat files in Python
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
Reading a MATLAB .mat file in Python is usually easy once you know which file format you are dealing with. The practical split is simple: traditional MAT files are commonly read with scipy.io.loadmat, while MATLAB v7.3 files are HDF5-based and are usually opened with h5py.
The first step is not writing code. It is understanding that “MAT file” can mean more than one storage format, and the correct library depends on that detail.
Read Standard MAT Files with SciPy
For many .mat files, scipy.io.loadmat is the default solution.
loadmat returns a dictionary-like object. Besides your variables, it often includes metadata keys such as __header__, __version__, and __globals__.
If the file contains a matrix saved in MATLAB under the name my_array, you can access it by that key. Numeric MATLAB arrays typically come back as NumPy arrays.
Make the Result Easier to Work With
MATLAB structs and squeezed dimensions can make the raw output awkward. loadmat has options that help.
squeeze_me=True removes unnecessary length-one dimensions, which often makes scalars and vectors much easier to use. struct_as_record=False can make MATLAB structs more convenient to inspect in Python code, depending on the file contents.
If you are exploring an unfamiliar file, start by printing the keys and the types of the returned values before writing any complicated parsing code.
Use h5py for MATLAB v7.3 Files
MATLAB v7.3 .mat files use HDF5 under the hood. Those are often not handled the same way as earlier MAT files, so h5py is a common solution.
The dataset[()] syntax reads the full dataset into memory as a NumPy array. If the file is large, you can slice it instead of loading everything at once.
One reason this matters is that users often see an error with loadmat, assume the file is corrupt, and stop there. In reality, the file may simply be a v7.3 HDF5-based MAT file that needs h5py.
Work with Nested Structures Carefully
MATLAB data can contain structs, cell arrays, and arrays with shapes that feel unusual from a Python perspective. Keep your inspection step explicit:
This lets you discover whether a given variable is a NumPy array, an object array, or a MATLAB-style struct representation. Once you know the shape and type, you can write clean conversion code instead of guessing.
A Practical Conversion Example
Here is a small helper that loads a named numeric variable and converts it to a pandas DataFrame.
This works well when the variable is a rectangular numeric matrix. If the MATLAB data is a cell array or nested struct, you will need custom extraction logic instead.
Common Pitfalls
The most common problem is using loadmat on a MATLAB v7.3 file and not realizing that the file is HDF5-based. When that happens, switch to h5py.
Another issue is assuming the returned values will always look exactly like the original MATLAB variables. Shape differences, object arrays, and metadata keys are normal, so inspect the structure before transforming it.
People also forget that .mat files can contain many variables, not just one. Hardcoding assumptions about the available keys often makes the script fragile.
Finally, loading the entire file into memory can be wasteful for large datasets. If you are using h5py, read only the slices you need. Even with loadmat, it is worth knowing the file size before building a memory-hungry pipeline around it.
Summary
- Use
scipy.io.loadmatfor many standard MATLAB.matfiles. - Use
h5pywhen the file is a MATLAB v7.3 HDF5-based MAT file. - Inspect keys and types before assuming how the data is structured.
- Options such as
squeeze_me=Trueandstruct_as_record=Falsecan make SciPy output easier to use. - Large MAT files may require selective reading rather than eager full-file loading.
Related reading
- Reading a file from a private S3 bucket to a pandas dataframe
- Real world typo statistics?
- Reasonable optimized chart scaling
- Recommendation engine without ratings
- Read only mode in keras
- Read only the first line of a file?
- Recommendations for using graphs theory in machine learning?
- Recommendations for using graphs theory in machine learning?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.