SciPy: Using io.savemat() function (4 examples)

Updated: March 7, 2024 By: Guest Contributor Post a comment

This tutorial aims to explore the io.savemat() function provided by SciPy, a fundamental library for scientific and technical computing in Python. The savemat() function is a part of the scipy.io module, which allows for interactions with MATLAB files. Through this guide, we will walk you through four comprehensive examples that incrementally increase in complexity to help you grasp the nuances of using io.savemat() effectively.

Understanding io.savemat()

Before diving into the examples, it’s essential to understand what io.savemat() does. Simply put, this function lets you save Python dictionaries to MATLAB .mat files, enabling MATLAB users to load and use Python-generated data seamlessly. The beauty of io.savemat() lies in its simplicity and efficiency in creating MATLAB-compatible files from Python’s extensive computational resources.

Setting Up Your Environment

To follow along with these examples, ensure your environment is set up with Python and SciPy installed. You can install SciPy using pip:

pip install scipy

Once installed, you’re ready to proceed with the examples below.

Example 1: Saving a Simple Dictionary

Our first example demonstrates how to save a simple dictionary containing numeric data into a .mat file. This acts as a foundational step for understanding io.savemat().

import scipy.io as sio
import numpy as np

data = {'x': np.array([1, 2, 3]), 'y': np.array([4, 5, 6])}
sio.savemat('example1.mat', data)

After running this code, you will find example1.mat in your current directory, which you can load in MATLAB to access the Python-generated x and y arrays.

Example 2: Saving a Nested Dictionary

Moving to a slightly more complex structure, this example showcases the ability to save a nested dictionary, further demonstrating io.savemat()‘s versatility.

import scipy.io as sio
import numpy as np

data = {
  'level1': {'a': np.array([1, 2, 3]), 'b': np.array([4, 5, 6])},
  'level2': {'c': np.array([7, 8, 9]), 'd': np.array([10, 11, 12])}
}
sio.savemat('example2.mat', data)

This code creates a example2.mat file containing the nested dictionary. When loaded in MATLAB, users can navigate through the ‘level1’ and ‘level2’ fields to access the numeric data.

Example 3: Including Metadata and Compression

Here, we add another layer of sophistication by including metadata within our .mat file and using the option to compress the file. This is particularly useful for saving space and adding context to the dataset.

import scipy.io as sio
import numpy as np

data = {'x': np.array([1, 2, 3]), 'y': np.array([4, 5, 6])}
metadata = {'description': 'Sample dataset', 'version': '1.0'}
sio.savemat('example3.mat', {'data': data, 'metadata': metadata}, do_compression=True)

The inclusion of metadata and compression significantly enhances the utility and efficiency of the .mat file created.

Example 4: Handling Complex Numbers and Structured Arrays

Our final example deals with more advanced data types, such as complex numbers and structured arrays, extending io.savemat()‘s applicability to sophisticated scientific computations.

import scipy.io as sio
import numpy as np

data = {'complex_data': np.array([1+2j, 3+4j, 5+6j]),
        'structured_data': np.array([(1, 'a'), (2, 'b')],
                                    dtype=[('num', 'O'), ('char', 'O')])}
sio.savemat('example4.mat', data)

This code snippet demonstrates the flexibility of io.savemat() in dealing with complex and structured data types, thereby broadening the scope for interdisciplinary data exchange.

Conclusion

Throughout this tutorial, we’ve explored the capabilities of the io.savemat() function through four illustrative examples. Starting from basic dictionary saving to handling complex data structures and incorporating compression and metadata, we’ve seen how savemat() facilitates seamless interaction between Python and MATLAB environments. Whether you’re working on academic research, industrial applications, or any project requiring interdisciplinary data exchange, understanding and utilizing io.savemat() effectively can significantly enhance your workflow and data management practices.