SciPy Matlab Arrays
scipy.io's savemat and loadmat functions let you exchange NumPy arrays with MATLAB's .mat file format, bridging Python and MATLAB workflows.
Why Exchange Data with MATLAB
Plenty of scientific and engineering teams still store and share data as MATLAB .mat files, even when the rest of a project has moved to Python. Rather than asking everyone to convert file formats, scipy.io lets you read and write .mat files directly, so a NumPy array computed in Python can be handed off to a MATLAB user (or the reverse) without any manual conversion. savemat takes a dictionary mapping variable names to NumPy arrays and writes all of them into a single .mat file.
Example
import numpy as np
from scipy.io import savemat
readings = np.array([21.5, 22.1, 19.8, 23.4, 20.0])
savemat("sensor_data.mat", {"readings": readings})Loading .mat Files Back into Python
loadmat reads a .mat file back into a Python dictionary, using the same variable names you originally saved under. Alongside your data, it also includes a handful of housekeeping keys such as __header__, __version__, and __globals__ that describe the file itself rather than your actual data.
Example
from scipy.io import loadmat
data = loadmat("sensor_data.mat")
print(data.keys()) # metadata keys plus your saved variable
print(data["readings"]) # comes back with shape (1, 5), not (5,)
print(data["readings"].shape)Example
clean_data = loadmat("sensor_data.mat", squeeze_me=True, mat_dtype=True)
print(clean_data["readings"]) # back to a flat 1-D array
print(clean_data["readings"].shape) # (5,)
print(np.array_equal(readings, clean_data["readings"])) # True- squeeze_me - removes extra length-1 dimensions so shapes come back closer to how NumPy would normally represent them
- mat_dtype - preserves the original MATLAB numeric type (MATLAB stores numbers as double by default)
- struct_as_record - controls whether MATLAB structs load as NumPy record arrays (the default) or as simpler Python objects
- simplify_cells - loads MATLAB cell arrays and structs as plain Python lists and dictionaries
Saving Several Variables at Once
savemat isn't limited to one array per file - pass a dictionary with several key/array pairs and every one of them is written into the same .mat file. When you load that file back, all of the variables appear together in the dictionary returned by loadmat, keyed by the same names you used when saving.
Exercise: SciPy Matlab Arrays
What is the purpose of the scipy.io module?