Written and maintained by CASRAI Editorial Board
Published
On this page
scipy.io.loadmat reads a MATLAB .mat file into Python and returns a dictionary whose keys are the MATLAB variable names and whose values are NumPy arrays. Its signature is scipy.io.loadmat(file_name, mdict=None, appendmat=True, *, spmatrix=..., **kwargs), and it supports MATLAB v4 (Level 1.0), v6 and v7 to 7.2 files. Files saved in MATLAB’s 7.3 format are HDF5 files and need an HDF5 library such as h5py instead.
This guide covers what the function does for researchers who receive instrument or simulation output as .mat files, how to install it, a step-by-step load with the arguments that matter, how to read the dictionary and the nested structures it returns, and how to fix the usual problems. It follows the SciPy reference page and the SciPy file-IO tutorial; the sources are listed at the end.
What scipy.io.loadmat is used for in research
Many labs, instruments and collaborators save data from MATLAB or Octave as .mat files. loadmat lets an analyst working in Python read those files directly, without exporting to CSV first, and keeps the array shapes and numeric types that MATLAB saved. The SciPy reference lists it with its companions in scipy.io: loadmat loads a MATLAB file, savemat writes one, and whosmat lists the variables inside a file without loading them.
The function is a reader for a particular binary container, not an analysis tool. Once the arrays are in memory they are ordinary NumPy arrays, so the next step is whatever your analysis needs. For plain-text numeric files use a different reader, as described in the guide to numpy.loadtxt; for writing data back out for MATLAB users, see the guide to saving data in MATLAB.
How to install or access scipy.io.loadmat
loadmat ships inside SciPy, so there is nothing separate to install. The SciPy installation page gives two official routes: with pip, run python -m pip install scipy inside an activated virtual environment; with conda, run conda install scipy (the conda-forge channel). The same page lists mamba as an alternative to conda. NumPy is a SciPy dependency and arrives with it.
The import follows the usual pattern, covered in the guide to importing SciPy:
from scipy.io import loadmat
# or
import scipy.io as sio
For MATLAB 7.3 files you also need an HDF5 library. The h5py documentation gives the two install commands: conda install h5py or pip install h5py. SciPy does not bundle an HDF5 library, which is why the loadmat reference page says one is needed for that format.
How to load a .mat file step by step
- Check what is inside the file. Call
whosmatfirst. It returns a list of tuples with each variable’s name, shape and class, for example[('a', (1, 3, 4), 'double')], without reading the data into memory.from scipy.io import whosmat whosmat('experiment.mat') - Load the file. Pass the file name. The
.matextension is optional whileappendmatis at its default ofTrue. The argument may also be an open file-like object.from scipy.io import loadmat mat = loadmat('experiment.mat') - Load only what you need. Give
variable_namesa sequence of strings; by default (None) every variable is read.mat = loadmat('experiment.mat', variable_names=['signal', 'params']) - Choose how structures and singleton dimensions are returned. For nested MATLAB structures or cell arrays,
simplify_cells=Trueis the shortest route; the next section explains the options.mat = loadmat('experiment.mat', simplify_cells=True) - Pull the variables out of the dictionary. Index by the MATLAB variable name.
signal = mat['signal'] print(signal.shape, signal.dtype)
The optional mdict argument is a dictionary into which the loaded variables are inserted, which is useful if you want to merge several files into one namespace. The reference page’s own worked example loads a test file with spmatrix=False, and then loads a structure file with squeeze_me=True to compare the shapes.
The arguments that change the result
Beyond the file name, the keyword arguments below change what comes back. The data table at the end of this page lists each one with its default and effect, taken from the reference page; the points below are the ones that most often decide whether code runs cleanly.
squeeze_meremoves unit matrix dimensions. A MATLAB scalar then arrives as a zero-dimensional value rather than a 1×1 array.struct_as_recorddefaults toTrue, which returns MATLAB structs as NumPy structured arrays. Setting it toFalsereturns them asmat_structobjects, so fields are read as attributes.simplify_cellsdefaults toFalse. Setting it toTruealso setsstruct_as_recordtoFalseandsqueeze_metoTrue, and is described as useful when the file contains cell arrays.matlab_compatibleimpliessqueeze_me=False,chars_as_strings=False,mat_dtype=Trueandstruct_as_record=True, giving arrays as MATLAB would load them.mat_dtypereturns arrays in the dtype MATLAB would load them with, instead of the dtype used to save them.spmatrixcontrols sparse output:Truereturns sparse matrices and otherwise sparse arrays are returned (COO for v4 files, CSC for v5). The reference page marks this argument as deprecated since SciPy 1.18.0, with the default changing toFalsein 1.20.
How to read the output
The return value, mat_dict, is a dictionary mapping variable names to arrays. Alongside your variables it contains metadata keys; the reference page gives __globals__, __header__ and __version__ as examples. Filter them out when you loop over the variables:
data = {k: v for k, v in mat.items() if not k.startswith('__')}
MATLAB arrays are always at least two-dimensional, and the SciPy tutorial shows this plainly. A variable created in Octave as a = reshape(1:12, [1 3 4]) and saved with save -6 loads with shape (1, 3, 4), and a NumPy np.arange(10) saved with savemat shows up in Octave as a 1×10 row vector. Expect a 1-D vector to come back as shape (1, N) unless you use squeeze_me=True. For more on handling those shapes afterwards, see the guide to NumPy arrays.
Structs and cell arrays: which option gives which result
The table below compares how a MATLAB struct is accessed under each setting, as described on the SciPy reference page and tutorial. It is the part of the output most users trip over.
| Setting | What a struct becomes | How to read a field |
|---|---|---|
| Defaults | A structured array of at least 2-D; a single struct loads with shape (1, 1) | val = oct_struct[0, 0] then val['field1'] |
squeeze_me=True |
The same structured array, with the (1, 1) shape squeezed to () | Index the squeezed array directly; the reference example shows the shape change |
struct_as_record=False |
mat_struct objects inside an object array |
oct_struct[0, 0].field1 (attribute access) |
struct_as_record=False with squeeze_me=True |
A scalar mat_struct object |
oct_struct.field1 |
simplify_cells=True |
A simplified dictionary structure (implies the two settings above) | Use dictionary-style access on the simplified result |
MATLAB cell arrays arrive as NumPy object arrays. When writing the reverse direction with savemat, the tutorial builds a cell array with np.zeros((2,), dtype=object), and a Python dictionary is saved as a MATLAB struct.
A worked round trip
This example is illustrative: it uses made-up values, not data from any study. It saves a small Python dictionary and reads it back with two different settings, to show how shapes change.
import numpy as np
from scipy.io import savemat, loadmat
savemat('demo.mat', {'x': np.arange(10), 'label': 'trial-1'})
a = loadmat('demo.mat')
print(a['x'].shape) # (1, 10): a row vector, as in MATLAB
b = loadmat('demo.mat', squeeze_me=True)
print(b['x'].shape) # (10,)
The first load keeps the MATLAB-style 1×10 shape that the tutorial describes for np.arange(10); the second squeezes it. Which you want depends on whether the downstream code expects MATLAB conventions or ordinary NumPy vectors.
Troubleshooting scipy.io.loadmat
The file is MATLAB 7.3 and loadmat cannot read it
The reference page supports v4, v6 and v7 up to 7.2 and states that an HDF5 library is needed for 7.3 files. Open those files with h5py, whose quick-start shows the pattern import h5py, f = h5py.File('mytestfile.hdf5', 'r') and list(f.keys()) to see what the file holds:
import h5py
with h5py.File('experiment.mat', 'r') as f:
print(list(f.keys()))
Datasets read through h5py come back as HDF5 datasets, not as the structured arrays that loadmat returns, so reshape and field handling differ. The CASRAI comparison of HDF5, Zarr and Parquet explains the container itself.
Data comes back with extra dimensions or nested arrays
This is the default behaviour, not a fault. Use squeeze_me=True for scalars and vectors, struct_as_record=False for attribute access to struct fields, or simplify_cells=True when cell arrays are involved.
Output looks different from MATLAB
Set matlab_compatible=True if you want arrays loaded with the settings MATLAB itself would use, or mat_dtype=True to restore the dtype MATLAB would assign.
Loading is slow or memory is high
Use whosmat to find the variable you need and pass its name in variable_names, so only that variable is read.
A corrupted-file error on a compressed file
verify_compressed_data_integrity defaults to True because overlong compressed sequences usually indicate file corruption. The reference page describes the check but does not recommend switching it off; try re-exporting the file from the source first.
Text decoding problems
For v6 and later files, uint16_codec sets the codec used to decode text; by default it is the system encoding. chars_as_strings controls whether character arrays are converted to string arrays.
Free alternatives to scipy.io.loadmat
Other routes to the same data are listed below, each with the situation the SciPy or h5py documentation ties it to.
| Option | When it applies | Where documented |
|---|---|---|
scipy.io.whosmat |
You only need the names, shapes and classes of the variables, not the data | SciPy file-IO tutorial |
| h5py | The file is MATLAB 7.3 (HDF5), which loadmat cannot read without an HDF5 library | loadmat reference page; h5py quick start |
| Re-save in an older format from Octave | You control the source and want a file loadmat reads directly; the tutorial’s Octave example uses save -6 |
SciPy file-IO tutorial |
| Plain-text export read with NumPy | The data is a simple numeric table | See the numpy.loadtxt guide |
Sources
- SciPy documentation: scipy.io.loadmat, checked 2026-11-17
- SciPy documentation: File IO tutorial (MATLAB files), checked 2026-11-17
- SciPy documentation: Input and output (scipy.io), checked 2026-11-17
- SciPy: Installing SciPy, checked 2026-11-17
- h5py documentation: Quick start guide, checked 2026-11-17
Data: scipy.io.loadmat keyword arguments: defaults and effects
Compiled from the SciPy scipy.io.loadmat reference page: each keyword argument that changes what loadmat returns, its documented default value and its documented effect on the returned dictionary.
| Argument | Default | Documented effect |
|---|---|---|
| appendmat | True | .mat extension is optional in file_name |
| mdict | None | Dictionary into which the loaded variables are inserted |
| variable_names | None (read all) | Sequence of variable names to read instead of all variables |
| squeeze_me | False | Squeezes unit matrix dimensions |
| struct_as_record | True | False returns mat_struct objects (attribute access) instead of structured arrays |
| simplify_cells | False | True returns a simplified dict structure; sets struct_as_record False and squeeze_me True |
| chars_as_strings | True | Converts char arrays to string arrays |
| mat_dtype | False | True returns arrays in the dtype MATLAB would load them with |
| matlab_compatible | False | Implies squeeze_me False, chars_as_strings False, mat_dtype True, struct_as_record True |
| verify_compressed_data_integrity | True | Checks the length of compressed sequences, since overlong ones usually indicate corruption |
| uint16_codec | System encoding | Codec for decoding text in v6 and later files |
| spmatrix | Changes to False in SciPy 1.20 | True returns sparse matrices, otherwise sparse arrays; deprecated since 1.18.0 |
Sources
- SciPy documentation: scipy.io.loadmat (accessed 2026-11-17)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







