SciPy - loadmat() Function



The scipy.io.loadmat() method reads MATLAB .mat files and converts their content to a Python dictionary.

MATLAB saves data to the .mat file format. This file can potentially include variables, arrays, matrices, and other structure elements. Loadmat() loads MATLAB data into python objects, such as the numpy array or dictionary.

This method is helpful in transferring data between MATLAB and Python. This can be used for importing MATLAB-processed data into Python-based machine learning or visualization. It is helpful in scientific computing, since it enables you to load MATLAB data for further processing or automate processes that mix MATLAB and Python operations.

MATLAB 1D arrays in Python can be represented as 2D arrays with one row. This can be solved by using squeeze_me() parameter to remove unnecessary dimensions. The loadmat() method can be paired with savemat() to edit and save MATLAB data after processing the data in Python.

Syntax

The syntax for the Scipy loadmat() method is as follows −

.loadmat(file_name, mdict=None, appendmat=True, **kwargs)

Parameters

This method accepts the following parameters −

  • file_name (str) − Name of the file or path of the .mat file to load.

  • mdict (dict, optional) A dictionary where the loaded variables are stored. If not provided, a new dictionary is created and returned.

  • appendmat (bool, optional) − If True, automatically appends .mat to the file_name if it doesnt already end with .mat.

  • **kwargs − This is used to handle specific file formats and data structures by allowing additional keyword arguments such as mat_dtype, squeeze_me, chars_as_strings, struct_as_record, and unicode_strings.

Return Value

dict − Where keys are variable names from the .mat file. Values are the corresponding data (e.g., NumPy arrays, nested dictionaries).

Example 1:

Using savemat and loadmat, Python can seamlessly save and load data in a format compatible with MATLAB.

In the below code we will see how to load the file into python using loadmat() method. First we save a python dictionary containing a matrix into MATLAB .mat file using savemat() method. Then we load the file into python. This shows how to share and reuse data between Python and MATLAB.

from scipy.io import savemat
from scipy.io import loadmat
# Save a simple dictionary to a .mat file
data_to_save = {'my_matrix': [[1, 2, 3], [4, 5, 6]]}
savemat('example.mat', data_to_save)

# Now load the file
data = loadmat('example.mat')
print("Loaded data: \n", data)

When we run above program, it produces following result −

Loaded data: 
 {'__header__': b'MATLAB 5.0 MAT-file Platform: posix, Created on: Wed Dec 18 04:44:54 2024', '__version__': '1.0', '__globals__': [], 'my_matrix': array([[1, 2, 3],
       [4, 5, 6]])}

Example 2

In this code we will use the same .mat file which was created in Example 1. In this example we used mdict parameter of loadmat() method to load the file's data directly into a custom directory, demonstrating efficient data mapping.

from scipy.io import loadmat

# Create an empty dictionary
my_dict = {}

# Load the .mat file into the dictionary
loadmat('example.mat', mdict=my_dict)

print("Custom dictionary keys:", my_dict.keys())

Following is an output of the above code −

Custom dictionary keys: dict_keys(['__header__', '__version__', '__globals__', 'my_matrix'])

Example 3

In the below code we will load the file into python using loadmat() method and then access the fields of the MATLAB structure. This example tell how structured data can be saved, loaded, and manipulated between Python and MATLAB.

import numpy as np
from scipy.io import savemat

data_to_save = {
    'my_struct': np.array([(np.array([1, 2, 3]), np.array([4, 5, 6]))], 
                          dtype=[('field1', 'O'), ('field2', 'O')])
}
savemat('example_struct.mat', data_to_save)

from scipy.io import loadmat
# Load the .mat file
data = loadmat('example_struct.mat')

# Access a MATLAB structure
matlab_struct = data['my_struct']

# Access fields within the structure
field1 = matlab_struct['field1'][0, 0]
field2 = matlab_struct['field2'][0, 0]

print("Field1 data:", field1)
print("Field2 data:", field2)
print(matlab_struct)

Following is an output of the above code −

Field1 data: [[1 2 3]]
Field2 data: [[4 5 6]]
[[(array([[1, 2, 3]]), array([[4, 5, 6]]))]]

Example 4

squeeze_me removes any singleton dimensions that are there (i.e., sizes equal to one) when the .mat file is loaded. Here's the code both with and without the squeeze_me argument to demonstrate how the loaded data would be different.

The output shows with squeez_me=True, it will remove the singleton dimension, which then results in a 2D matrix of shape (2,2). Without squeeze_me, the 3D shape (1, 2, 2) is retained, even with the redundant singleton dimension. Comparing the output you see how squeeze_me simplifies the array structure on loading the.mat file.

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

# Save a simple 3D matrix to a .mat file
data_to_save = {'my_matrix': np.array([[[1, 2], [3, 4]]], dtype=np.float32)}  # Explicitly 3D
savemat('example.mat', data_to_save)

# Load with squeeze_me=True
data = loadmat('example.mat', squeeze_me=True)
matrix = data['my_matrix']
print("\nMatrix Data (with squeeze):\n", matrix)
print("Shape of the matrix with squeeze:", matrix.shape)

# Load without squeeze
data = loadmat('example.mat')  # Default behavior, no squeeze
matrix = data['my_matrix']
print("\nMatrix Data (without squeeze):\n", matrix)
print("Shape of the matrix without squeeze:", matrix.shape)

Output of the above code is as follows −

Matrix Data:
 [[[1 2]
  [3 4]]]

Shape of the matrix with squeeze: (2, 2)

Matrix Data:
 [[[1 2]
  [3 4]]]

Shape of the matrix without squeeze: (1, 2, 2)

Matrix Data:
 [[[1 2]
  [3 4]]]
scipy_input_output.htm
Advertisements