savemat() takes a dict mapping variable names to their values, usually NumPy arrays, and writes them into a .mat file in MATLAB's own binary format, which MATLAB can then load directly with its own load function, or another SciPy script can load back with loadmat(). Since MATLAB doesn't have a native concept of a 1D array the way NumPy does, a plain 1D NumPy array gets saved, and reloaded, as a 2D row or column matrix instead, which is a common, easily-missed source of shape mismatches when round-tripping data between the two.
1Understanding io.savemat()
savemat() takes a dict mapping variable names to their values, usually NumPy arrays, and writes them into a .mat file in MATLAB's own binary format, which MATLAB can then load directly with its own load function, or another SciPy script can load back with loadmat(). Since MATLAB doesn't have a native concept of a 1D array the way NumPy does, a plain 1D NumPy array gets saved, and reloaded, as a 2D row or column matrix instead, which is a common, easily-missed source of shape mismatches when round-tripping data between the two.
Remember MATLAB has no true 1D array — saving a plain 1D NumPy array with savemat() and loading it back with loadmat() typically returns a 2D array, a single row or column, instead of the original 1D shape, so don't assume a perfect round-trip of array dimensionality.
from scipy.io import savemat
import numpy as np
data = {"measurements": np.array([1.5, 2.3, 3.1])}
savemat("data.mat", data)
print("Saved successfully")2Practical Example
Here is a real-world application of io.savemat() showing how it is used in production SciPy code.
from scipy.io import savemat, loadmat
import numpy as np
savemat("data.mat", {"arr": np.array([1, 2, 3])})
loaded = loadmat("data.mat")
print(loaded["arr"].shape)3Best Practices
Follow these guidelines when working with io.savemat():
1. Use savemat() specifically when data needs to be shared with, or was originally produced by, MATLAB code, rather than for pure Python-to-Python data exchange
2. Expect and handle the 1D-to-2D shape change that occurs when saving a 1D array through savemat() and reloading it, rather than assuming an exact shape round-trip
3. Prefer np.save()/np.savez() over savemat() for pure Python workflows, since they preserve NumPy's exact shapes and dtypes without any MATLAB-compatibility conversions
Tip: Remember MATLAB has no true 1D array — saving a plain 1D NumPy array with savemat() and loading it back with loadmat() typically returns a 2D array, a single row or column, instead of the original 1D shape, so don't assume a perfect round-trip of array dimensionality.
from scipy.io import savemat
import numpy as np
data = {"measurements": np.array([1.5, 2.3, 3.1])}
savemat("data.mat", data)
print("Saved successfully")