HOWTO · Python
How to Read Matlab mat Files in Python
This tutorial demonstrates how to read and open Matlab .mat files in Python. Learn effective methods using libraries like SciPy, h5py, and Mat4py to access and manipulate your data seamlessly. Whether you're dealing with v7 or v7.3 files, this guide has you covered. Enhance your data analysis skills today!
On this page
MATLAB saves workspace variables in .mat files, and Python has no built-in way to open them — you pick a reader library based on the MAT-file version. This guide shows how to identify the format of a file and load its variables with scipy.io, h5py, mat4py, or the matlab.engine API, and it explains where each approach stops working.
Choose a reader for the MAT-file version
MATLAB has used two file layouts. MAT-file versions 5 through 7.2 use MATLAB’s own binary format and begin with a 128-byte text header that starts with MATLAB; the still older MATLAB 4 files use the same classic layout but have no descriptive header — they begin directly with data elements. scipy.io.loadmat reads the whole classic family, header or not. Files saved with -v7.3 are HDF5 files: they keep a small MATLAB user block but store the data as HDF5 datasets, which is what h5py opens. NumPy by itself cannot open either layout — it only converts an already-loaded dataset into an array.
You can identify a file without installing anything by looking at its first bytes. Run this example, which writes one file of each common kind to a temporary folder and classifies them by header:
import os
import tempfile
folder = tempfile.mkdtemp()
classic = os.path.join(folder, "classic.mat")
modern = os.path.join(folder, "v73.mat")
with open(classic, "wb") as f:
f.write(b"MATLAB 5.0 MAT-file, Platform: GLNXA64, Created on: Thu Oct 29 2026".ljust(128, b" "))
with open(modern, "wb") as f:
f.write(b"MATLAB 7.3 MAT-file, Platform: GLNXA64, HDF5 schema 1.00".ljust(512, b" "))
f.write(b"\x89HDF\r\n\x1a\n")
def mat_kind(path):
with open(path, "rb") as f:
head = f.read(128)
f.seek(512)
signature = f.read(8)
if b"HDF5" in head or signature.startswith(b"\x89HDF"):
return "MATLAB 7.3 (HDF5): read with h5py"
if head.startswith(b"MATLAB"):
return "MAT-file 7.2 or older: read with scipy.io.loadmat"
return "no v5+ header or HDF5 signature — possibly a MATLAB 4 file: try scipy.io.loadmat"
print(mat_kind(classic))
print(mat_kind(modern))
MAT-file 7.2 or older: read with scipy.io.loadmat
MATLAB 7.3 (HDF5): read with h5py
A real 7.3 file mentions HDF5 in its header text and carries the HDF5 signature after the user block, while a version 5–7.2 file’s header simply starts with MATLAB. The check classifies only by those two markers: a MATLAB 4 file shows neither, so it lands on the fallback message — but scipy.io.loadmat still opens it, so treat that result as a cue to try loadmat directly rather than proof the file is unreadable. As a rule, reach for scipy.io.loadmat first when the file is version 7.2 or older, use h5py for 7.3 files, pick mat4py when you want plain Python lists instead of NumPy arrays from a classic file, and use matlab.engine only when MATLAB itself is installed and you need full fidelity for complex types. Once the variables are in Python, pandas can export them to CSV or Excel, and scipy.io.savemat or an HDF5 dataset can write a .mat file back if you later need one.
The sections below use sample.mat (a classic file) and sample_v73.mat (a 7.3 file) that are assumed to contain a variable named measurements. Those snippets are dependency-specific: they assume the named package is installed, so run them in your own environment rather than in a bare interpreter.
Read MATLAB files with SciPy
Install the library with pip install scipy, then call scipy.io.loadmat("sample.mat"). It returns a dictionary: alongside your variables it carries the metadata keys __header__, __version__, and __globals__, and every MATLAB variable becomes a NumPy array under its workspace name, so data["measurements"] retrieves that variable directly.
Two options are worth knowing when the shapes look off. Passing squeeze_me=True to loadmat collapses MATLAB’s singleton dimensions so a scalar comes back as a scalar, and combining it with struct_as_record=False lets you reach struct fields as attributes instead of nested array elements. To write results back, scipy.io.savemat("out.mat", {"measurements": data["measurements"]}) produces a classic MAT-file.
The version limit is the important restriction: loadmat supports MAT-file formats through 7.2 only. Given a 7.3 file it reports the format as unsupported, because the payload is HDF5 — that file needs the approach in the next section. If you control the MATLAB side, saving with save data.mat -v7 produces a file loadmat accepts.
Read MATLAB 7.3 files with h5py
A -v7.3 file is HDF5 with a MATLAB user block, so pip install h5py is all you need to open it. h5py.File("sample_v73.mat", "r") opens the file for reading, and list(f.keys()) shows the top-level groups — one per MATLAB variable plus a #refs# group that stores shared cell and struct content.
Reading f["measurements"][()] materializes the dataset as a NumPy array; NumPy is only converting the data here, since h5py opened the file. Two layout details matter in practice. MATLAB writes arrays column-major, so a 2-D dataset commonly comes back transposed, and f["measurements"][()].T restores the MATLAB orientation. Cell arrays and structs arrive as HDF5 object references into #refs#, so you dereference each entry with f[ref] instead of reading it directly.
Read MATLAB files with mat4py
pip install mat4py gives you a smaller API aimed at classic MAT-files. After from mat4py import loadmat, calling loadmat("sample.mat") returns an ordinary dictionary in which numeric arrays are nested Python lists and structs become nested dictionaries — convenient when you want the data as pure Python types without pulling in NumPy.
Treat mat4py as a reader for the classic formats: it does not open 7.3 HDF5 files, and deeply nested or unusual MATLAB structures may not map cleanly, so it is not a substitute for every MAT-file. Verify a complex file’s conversion against scipy.io before building on it.
Read MATLAB files with the MATLAB Engine API
When MATLAB itself is installed, its Engine API for Python is the highest-fidelity option. Installing matlabengine with pip (or running the installer shipped with MATLAB) exposes matlab.engine, which drives a real MATLAB session behind the scenes. eng = matlab.engine.start_matlab() launches that session, eng.load("sample.mat") loads every variable into the engine workspace regardless of the file version, and eng.quit() closes it when you are done. Values come back as MATLAB types such as matlab.double, which NumPy converts with np.asarray.
The trade-offs are practical rather than format-related: the engine needs a licensed MATLAB installation and a matching engine version, the session takes seconds to start, and it cannot run in a plain Python environment. That is also why this section shows the calls inline instead of as a standalone example — the other libraries are the right default whenever MATLAB is not already on the machine.