Read .mat files in Python
The scipy.io.loadmat method allows you to import .mat files effortlessly in Python:
Replace 'insert_your_file_path' with the path of your .mat file and 'variable_name' with the specific variable you want to extract from MATLAB. Ensure you installed SciPy, and the version you're using is 0.7.0 or higher to be able to call loadmat().
Alternate solutions for different MATLAB versions
For .mat files from MATLAB v7.3, using h5py package might be beneficial as these files are stored as HDF5:
Another alternate is mat4py, which can be installed via pip and provides read and write access to .mat files, handling them as dictionaries and lists:
Saving files in .mat format with Python
Save your Python data to a .mat file with the -v7 option for backward compatibility:
Diving into the data
After you've successfully imported your .mat file, top-level MATLAB variables are converted into a Python dictionary. The keys are MATLAB variable names. Familiarize yourself with the structure to navigate through the data efficiently.
Accessing variables
Extracting and working with the variables is straightforward:
Converting to NumPy array
To convert the imported data to a NumPy array:
Deep dive with the MATLAB engine
If you have MATLAB installed, the MATLAB Engine for Python allows you to call MATLAB functions:
The nargout=1 parameter ensures MATLAB returns the data to Python.
Working with advanced .mat files using h5py
The h5py library is particularly useful while dealing with MATLAB v7.3 files:
Don't forget, knowing the exact structure of your .mat file is critical here.
When more conversion is needed
mat4py can also convert data to JSON-compatible format:
And the squeezing feature removes single-element arrays:
Was this article helpful?