SciPy Matlab Arrays
Many labs and engineering teams store data in MATLAB's .mat format. The scipy.io module can write NumPy arrays into .mat files with savemat() and read them back with loadmat(), so Python and MATLAB users can share data.
Normally you pass a file name. In this course the code runs in your browser, so we use an in-memory io.BytesIO buffer instead — it behaves like an open binary file, and the code is otherwise exactly what you'd write for a real file.
# With real files you would write:
savemat("measurements.mat", {"temps": temps})
data = loadmat("measurements.mat")Saving arrays
savemat() takes a file (name or file-like object) and a dictionary: each key becomes a MATLAB variable name.
import io
import numpy as np
from scipy.io import savemat
temps = np.array([21.5, 22.0, 23.1, 22.7])
grid = np.arange(6).reshape(2, 3)
buffer = io.BytesIO()
savemat(buffer, {"temps": temps, "grid": grid})
print("bytes written:", len(buffer.getvalue()))
print("file header :", buffer.getvalue()[:19].decode())bytes written: 304
file header : MATLAB 5.0 MAT-file
The header is plain text that MATLAB uses to recognise the file.
Loading arrays
loadmat() returns a dictionary. Besides your variables it contains three metadata entries whose names start with __:
import io
import numpy as np
from scipy.io import savemat, loadmat
buffer = io.BytesIO()
savemat(buffer, {"temps": np.array([21.5, 22.0, 23.1, 22.7]),
"grid": np.arange(6).reshape(2, 3)})
buffer.seek(0) # rewind before reading
data = loadmat(buffer)
print(sorted(k for k in data if not k.startswith("__")))
print("temps:", data["temps"], data["temps"].shape)
print("grid:")
print(data["grid"])['grid', 'temps']
temps: [[21.5 22. 23.1 22.7]] (1, 4)
grid:
[[0 1 2]
[3 4 5]]
Notice that temps came back with shape (1, 4), not (4,). MATLAB has no 1-D arrays: every array is at least 2-D, so a vector is stored as a 1 × N row.
Getting 1-D arrays back
There are two easy fixes: pass squeeze_me=True to loadmat(), which removes length-1 dimensions, or flatten the array yourself:
import io
import numpy as np
from scipy.io import savemat, loadmat
buffer = io.BytesIO()
savemat(buffer, {"temps": np.array([21.5, 22.0, 23.1, 22.7]), "count": 4})
buffer.seek(0)
plain = loadmat(buffer)
buffer.seek(0)
squeezed = loadmat(buffer, squeeze_me=True)
print("default :", plain["temps"].shape, plain["count"])
print("squeezed:", squeezed["temps"].shape, squeezed["count"])
print("ravel() :", plain["temps"].ravel())default : (1, 4) [[4]]
squeezed: (4,) 4
ravel() : [21.5 22. 23.1 22.7]
Even the scalar count became a 1 × 1 array by default.
Strings, structs and cell arrays
savemat() converts more than numeric arrays:
| Python value | Saved as MATLAB |
|---|---|
| NumPy numeric array | numeric matrix |
str |
char array |
dict |
struct |
| list of mixed objects / object array | cell array |
bool array |
logical array |
import io
import numpy as np
from scipy.io import savemat, loadmat
experiment = {
"name": "pendulum",
"settings": {"length": 0.75, "trials": 3},
"periods": np.array([1.73, 1.74, 1.72]),
}
buffer = io.BytesIO()
savemat(buffer, experiment)
buffer.seek(0)
data = loadmat(buffer, squeeze_me=True, simplify_cells=True)
print("name :", data["name"])
print("settings:", data["settings"])
print("periods :", data["periods"])name : pendulum
settings: {'length': 0.75, 'trials': 3}
periods : [1.73 1.74 1.72]
simplify_cells=True turns MATLAB structs back into plain Python dictionaries, which is usually what you want.
Inspecting a file without loading it
For large files, whosmat() lists the variables, their shapes and types without reading the data:
import io
import numpy as np
from scipy.io import savemat, whosmat
buffer = io.BytesIO()
savemat(buffer, {"image": np.zeros((480, 640), dtype=np.uint8),
"labels": np.array([1.0, 2.0, 3.0])})
buffer.seek(0)
for name, shape, kind in whosmat(buffer):
print(f"{name:7} {str(shape):11} {kind}")image (480, 640) uint8
labels (1, 3) double
Tip:
savemat()writes the MATLAB 5 format by default. For very large arrays (over 2 GB) MATLAB uses the 7.3 format, which is HDF5 under the hood — read those with theh5pypackage instead ofscipy.io.
Test yourself
What kind of object does savemat() expect for the data?
- A list of arrays
- A dictionary mapping variable names to values
- A single NumPy array
- A pandas DataFrame
You save a 1-D array of 5 numbers and load it back. What shape does it have by default?
- (5,)
- (5, 1)
- (1, 5)
- (1, 1, 5)
Why must you call buffer.seek(0) before loadmat(buffer)?
- To clear the buffer
- Writing left the position at the end, so reading must start from the beginning
- loadmat requires it for compression
- To convert it to text