MATLAB MAT files are a common handoff format when Python data has to move into MATLAB, Octave, or an older analysis archive. SciPy can read and write many .mat files directly, which avoids a separate conversion script when arrays, labels, and small metadata structures need to travel together.
The scipy.io.savemat() function writes a dictionary of variable names and arrays into a MAT file. Pairing it with scipy.io.whosmat() and scipy.io.loadmat() lets you inspect the file inventory, load the saved variables, and verify that the shapes and values survived the round trip.
A current SciPy MAT-file round trip covers MATLAB v4 (Level 1.0), v6, and v7 through v7.2 files. MATLAB 7.3 files are HDF5 backed, so open those with an HDF5 reader such as h5py instead of expecting loadmat() to handle that format.
Steps to read and write MATLAB MAT files with SciPy:
- Create a Python script named mat_file_roundtrip.py.
- mat_file_roundtrip.py
import numpy as np from scipy.io import loadmat, savemat, whosmat temperatures = np.array(((21.5, 22.1, 22.8), (20.9, 21.7, 22.4))) sample_ids = np.array([101, 102, 103], dtype=np.int32) metadata = {"site": "lab-a", "unit": "celsius"} savemat( "experiment.mat", { "temperatures": temperatures, "sample_ids": sample_ids, "metadata": metadata, }, oned_as="column", ) print("variables:") for name, shape, dtype in whosmat("experiment.mat"): print(f" {name}: shape={shape}, class={dtype}") mat = loadmat("experiment.mat", simplify_cells=True) print("loaded keys:", sorted(k for k in mat if not k.startswith("__"))) print("temperatures shape:", mat["temperatures"].shape) print("sample_ids shape:", mat["sample_ids"].shape) print("first temperature:", mat["temperatures"][0, 0]) print("site:", mat["metadata"]["site"]) print("round_trip_ok:", bool(np.allclose(mat["temperatures"], temperatures)))
oned_as=“column” writes the one-dimensional sample_ids array as a MATLAB column vector. Omit it when a row vector is the intended MATLAB shape.
- Run the script to save, inspect, and reload the MAT file.
$ python mat_file_roundtrip.py variables: temperatures: shape=(2, 3), class=double sample_ids: shape=(3, 1), class=int32 metadata: shape=(1, 1), class=struct loaded keys: ['metadata', 'sample_ids', 'temperatures'] temperatures shape: (2, 3) sample_ids shape: (3,) first temperature: 21.5 site: lab-a round_trip_ok: True
- Check the MAT-file inventory before reading values into later calculations.
whosmat() reports each variable name, shape, and MATLAB data class without loading array values into your Python variables.
- Confirm that only the expected variables were loaded.
loadmat() also returns metadata keys such as header, version, and globals. Filtering names that start with __ keeps the check focused on saved MATLAB variables.
- Review shape changes from simplified loading.
simplify_cells=True squeezes length-one dimensions, so the saved sample_ids column vector reloads as a one-dimensional array with shape (3,).
- Use the round-trip comparison before passing the file to another tool.
round_trip_ok: True confirms the numeric array survived the save/load path within floating-point comparison tolerance.
- Remove the temporary script and MAT file when the round-trip test was only for validation.
$ rm mat_file_roundtrip.py experiment.mat
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.