Working with MATLAB-style Arrays in Python using SciPy

Last updated 3 months, 3 weeks ago | 223 views 75     5

Tags:- Python SciPy

Python and MATLAB are both powerful environments for scientific computing. If you’re coming from a MATLAB background or need MATLAB-like functionality in Python, SciPy provides a convenient way to work with MATLAB-style arrays through the scipy.io module.

In this article, you'll learn:

  • How SciPy integrates with MATLAB files

  • How to load and save .mat files

  • How to access MATLAB arrays in Python

  • Complete examples with tips and common pitfalls


What Are MATLAB Arrays?

MATLAB arrays are matrices or multi-dimensional arrays stored in .mat files. These arrays can contain numbers, strings, structures, or even cell arrays.

SciPy allows Python users to interact with .mat files directly, which makes it easy to read data generated in MATLAB or share data across platforms.


Required Modules

Make sure you have scipy and numpy installed:

pip install scipy numpy

Import the required libraries:

from scipy.io import loadmat, savemat
import numpy as np

Loading MATLAB .mat Files

Use loadmat() to load MATLAB files into a Python dictionary.

Example: Loading a .mat file

from scipy.io import loadmat

data = loadmat('example.mat')

# View keys in the dictionary
print(data.keys())

# Access a variable
matrix = data['my_array']
print(matrix)

Notes:

  • The .mat file must be in MATLAB v5 format or later.

  • MATLAB variables are loaded as NumPy arrays.


Saving Data to .mat Files

Use savemat() to save Python variables to a .mat file.

Example: Saving to a .mat file

from scipy.io import savemat
import numpy as np

arr = np.array([[1, 2], [3, 4]])

# Save to file
savemat('saved_data.mat', {'my_array': arr})

This creates a MATLAB-readable .mat file with the variable my_array.


Full Example: Load, Modify, and Save .mat File

from scipy.io import loadmat, savemat
import numpy as np

# Load existing .mat file
data = loadmat('example.mat')
matrix = data['my_array']
print("Original matrix:\n", matrix)

# Perform an operation (e.g., add 10)
modified = matrix + 10

# Save modified data to a new file
savemat('modified.mat', {'my_array': modified})

print("Modified matrix saved.")

Understanding the Dictionary Structure

When you load a .mat file, it returns a dictionary with these elements:

{
 '__header__': b'MATLAB 5.0 MAT-file Platform...',
 '__version__': '1.0',
 '__globals__': [],
 'variable_name': np.array(...)
}
  • __header__, __version__, and __globals__ are metadata.

  • The actual variables are accessible by their original names.


Working with Structured Arrays

MATLAB structs become nested NumPy structured arrays in Python.

struct_data = data['my_struct']
print(struct_data.dtype)

You’ll often need to access .item() and fields like:

value = struct_data['fieldname'][0][0]

✅ Tips for Using MATLAB Arrays in Python

Tip Description
Use squeeze_me=True in loadmat() Automatically removes extra dimensions
Use do_compression=True in savemat() Saves space in large files
Check MATLAB version compatibility Use MATLAB v5 or newer format
Convert complex types carefully Complex numbers and objects need special handling

Common Pitfalls

Pitfall Solution
Unexpected extra dimensions Use squeeze() on loaded arrays
Unable to open .mat file Ensure it’s in MATLAB v5 format
Field names not found Double-check structure indexing, especially with nested structs
Compatibility issues Avoid using MATLAB-specific objects like tables, cell arrays, or objects if possible

Summary

Feature SciPy Function
Load .mat file loadmat()
Save .mat file savemat()
Access matrix data Dictionary access (data['var'])
Support for structs Yes (with nested NumPy structures)

SciPy's io module acts as a bridge between MATLAB and Python, enabling seamless exchange of matrix data. Whether you're transitioning from MATLAB or integrating cross-platform workflows, this feature ensures productivity and compatibility.


Final Thoughts

Python with SciPy provides an excellent alternative to MATLAB for scientific and numerical computing. The ability to read and write .mat files means you can collaborate easily with MATLAB users or reuse existing datasets.

If you're working with more complex MATLAB objects or GUIs, consider using MATLAB Engine API for Python or exporting data in CSV/JSON formats.