Python
.mat files
file handling
data analysis
scipy

How to read .mat files in Python (scipy.io.loadmat and h5py)

Codemia Knowledge Hub ·

Yes, Python can read MATLAB .mat files. Traditional MAT files are read with scipy.io.loadmat, while MATLAB v7.3 files are HDF5-based and are usually opened with h5py. So before writing code, find out which format your file uses, because that decides the library.

Read standard MAT files with SciPy

For many .mat files, scipy.io.loadmat is all you need.

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__.

A matrix saved in MATLAB as my_array is available under that key. Numeric MATLAB arrays typically come back as NumPy arrays.

Clean up structs and extra dimensions

MATLAB structs and length-one 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 makes scalars and vectors much easier to use. struct_as_record=False can make MATLAB structs more convenient to inspect from Python, depending on the file contents.

With an unfamiliar file, print 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 and are often not handled the same way as earlier MAT files, so h5py is the common choice.

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)

dataset[()] reads the full dataset into memory as a NumPy array. For a large file, slice it instead of loading everything at once.

This matters because people often get an error from loadmat, assume the file is corrupt, and stop there. Often the file is simply a v7.3 HDF5-based MAT file that needs h5py.

Inspect nested structures first

MATLAB data can contain structs, cell arrays, and arrays with shapes that look unusual from Python. Make the 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 shows whether each 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.

Convert a variable to a pandas DataFrame

This helper loads a named numeric variable and converts it to a 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)

It works when the variable is a rectangular numeric matrix. Cell arrays and nested structs need custom extraction logic.

Mistakes that break MAT file loading

  • Using loadmat on a v7.3 file: the file is HDF5-based. Switch to h5py.
  • Expecting an exact copy of the MATLAB variables: shape differences, object arrays and metadata keys are normal, so inspect the structure before transforming it.
  • Hardcoding keys: a .mat file can hold many variables, and assumptions about which keys exist make scripts fragile.
  • Loading everything into memory: for large datasets this is wasteful. With h5py, read only the slices you need. With loadmat, know the file size before building a memory-hungry pipeline around it.

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
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
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