0
0
SciPydata~5 mins

MATLAB file I/O (loadmat, savemat) in SciPy

Choose your learning style9 modes available
Introduction

We use MATLAB file I/O to read and write MATLAB data files in Python. This helps us share data between MATLAB and Python easily.

You have data saved in a MATLAB .mat file and want to analyze it in Python.
You want to save Python data so MATLAB can open and use it.
You are working on a project that uses both MATLAB and Python and need to exchange data files.
You want to load MATLAB results into Python for visualization or further processing.
You want to save Python arrays or dictionaries into a .mat file for MATLAB users.
Syntax
SciPy
from scipy.io import loadmat, savemat

# Load MATLAB file
data = loadmat('filename.mat')

# Save data to MATLAB file
savemat('filename.mat', {'variable_name': data_to_save})

loadmat loads MATLAB .mat files into a Python dictionary.

savemat saves Python dictionaries to .mat files readable by MATLAB.

Examples
This loads the MATLAB file 'data.mat' into a Python dictionary called mat_data.
SciPy
from scipy.io import loadmat
mat_data = loadmat('data.mat')
This saves a NumPy array as my_array in the MATLAB file 'output.mat'.
SciPy
from scipy.io import savemat
import numpy as np

array = np.array([1, 2, 3])
savemat('output.mat', {'my_array': array})
Sample Program

This program saves a dictionary with scores and names to a MATLAB file, then loads it back and prints the contents.

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

# Create some data to save
my_dict = {'scores': np.array([90, 85, 88]), 'names': np.array(['Ann', 'Bob', 'Cara'], dtype=object)}

# Save data to MATLAB file
savemat('example.mat', my_dict)

# Load the data back
loaded_data = loadmat('example.mat')

# Print loaded data keys and values
for key in loaded_data:
    if not key.startswith('__'):
        print(f"{key}: {loaded_data[key]}")
OutputSuccess
Important Notes

MATLAB .mat files store data in a dictionary-like structure when loaded in Python.

Keys starting with '__' in loaded data are metadata and can be ignored.

Use dtype=object for string arrays to avoid issues when saving/loading.

Summary

Use loadmat to read MATLAB .mat files into Python dictionaries.

Use savemat to save Python dictionaries as MATLAB .mat files.

This allows easy data exchange between MATLAB and Python.