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.
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.
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.
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:
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:
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
loadmaton a v7.3 file: the file is HDF5-based. Switch toh5py. - 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
.matfile 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. Withloadmat, know the file size before building a memory-hungry pipeline around it.
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?
- Recommended anomaly detection technique for simple, one-dimensional scenario?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.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 courseNo 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 courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.