Python
.mat files
file handling
data analysis
scipy

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.

Practice ML system design

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.

python
1from scipy.io import loadmat
2
3data = loadmat("example.mat")
4
5print(data.keys())
6print(data["my_array"])

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.

python
1from scipy.io import loadmat
2
3data = loadmat(
4    "example.mat",
5    squeeze_me=True,
6    struct_as_record=False
7)
8
9record = data["experiment"]
10print(record.subject_id)
11print(record.score)

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.

python
1import h5py
2
3with h5py.File("example_v73.mat", "r") as file:
4    print(list(file.keys()))
5
6    dataset = file["my_array"]
7    values = dataset[()]
8    print(values)

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:

python
1from scipy.io import loadmat
2
3data = loadmat("example.mat", squeeze_me=True, struct_as_record=False)
4
5for key, value in data.items():
6    if not key.startswith("__"):
7        print(key, type(value))

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.

python
1import pandas as pd
2from scipy.io import loadmat
3
4
5def mat_variable_to_dataframe(path, variable_name):
6    data = loadmat(path)
7    array = data[variable_name]
8    return pd.DataFrame(array)

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.loadmat for many standard MATLAB .mat files.
  • Use h5py when 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=True and struct_as_record=False can make SciPy output easier to use.
  • Large MAT files may require selective reading rather than eager full-file loading.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Practice ML system design

All Rights Reserved.