loadmat() returns a dict where each MATLAB variable's name becomes a key and its data becomes a NumPy array value, along with a handful of extra metadata keys, like header, version, and globals keys, that describe the file itself rather than actual saved variables. As with savemat(), any 1D array data ends up represented as a 2D array, a single row or column, since that's how MATLAB itself represents it, which is important to remember when using the loaded data in further NumPy computations expecting a flat 1D shape.
1Understanding io.loadmat()
loadmat() returns a dict where each MATLAB variable's name becomes a key and its data becomes a NumPy array value, along with a handful of extra metadata keys, like header, version, and globals keys, that describe the file itself rather than actual saved variables. As with savemat(), any 1D array data ends up represented as a 2D array, a single row or column, since that's how MATLAB itself represents it, which is important to remember when using the loaded data in further NumPy computations expecting a flat 1D shape.
Filter out the metadata keys, those starting and ending with double underscores, when iterating over a loaded .mat file's variables — loadmat() always includes them alongside your actual saved data.
from scipy.io import savemat, loadmat
import numpy as np
savemat("data.mat", {"scores": np.array([85, 90, 78])})
loaded = loadmat("data.mat")
print(loaded["scores"])2Practical Example
Here is a real-world application of io.loadmat() showing how it is used in production SciPy code.
from scipy.io import savemat, loadmat
import numpy as np
savemat("data.mat", {"scores": np.array([85, 90, 78])})
loaded = loadmat("data.mat")
print(list(loaded.keys()))3Best Practices
Follow these guidelines when working with io.loadmat():
1. Filter out or skip the dunder metadata keys when iterating over loadmat()'s returned dict, since they aren't actual saved variables
2. Use .squeeze() or .ravel() on loaded array data if you specifically need it back in a flat 1D shape instead of MATLAB's inherent 2D row/column representation
3. Use io.whosmat() first to inspect a .mat file's variable names and shapes before loading its full contents, if you only need to check what's inside without loading all the actual data
Tip: Filter out the metadata keys, those starting and ending with double underscores, when iterating over a loaded .mat file's variables — loadmat() always includes them alongside your actual saved data.
from scipy.io import savemat, loadmat
import numpy as np
savemat("data.mat", {"scores": np.array([85, 90, 78])})
loaded = loadmat("data.mat")
print(loaded["scores"])