
- SciPy - Home
- SciPy - Introduction
- SciPy - Environment Setup
- SciPy - Basic Functionality
- SciPy - Relationship with NumPy
- SciPy Clusters
- SciPy - Clusters
- SciPy - Hierarchical Clustering
- SciPy - K-means Clustering
- SciPy - Distance Metrics
- SciPy Constants
- SciPy - Constants
- SciPy - Mathematical Constants
- SciPy - Physical Constants
- SciPy - Unit Conversion
- SciPy - Astronomical Constants
- SciPy - Fourier Transforms
- SciPy - FFTpack
- SciPy - Discrete Fourier Transform (DFT)
- SciPy - Fast Fourier Transform (FFT)
- SciPy Integration Equations
- SciPy - Integrate Module
- SciPy - Single Integration
- SciPy - Double Integration
- SciPy - Triple Integration
- SciPy - Multiple Integration
- SciPy Differential Equations
- SciPy - Differential Equations
- SciPy - Integration of Stochastic Differential Equations
- SciPy - Integration of Ordinary Differential Equations
- SciPy - Discontinuous Functions
- SciPy - Oscillatory Functions
- SciPy - Partial Differential Equations
- SciPy Interpolation
- SciPy - Interpolate
- SciPy - Linear 1-D Interpolation
- SciPy - Polynomial 1-D Interpolation
- SciPy - Spline 1-D Interpolation
- SciPy - Grid Data Multi-Dimensional Interpolation
- SciPy - RBF Multi-Dimensional Interpolation
- SciPy - Polynomial & Spline Interpolation
- SciPy Curve Fitting
- SciPy - Curve Fitting
- SciPy - Linear Curve Fitting
- SciPy - Non-Linear Curve Fitting
- SciPy - Input & Output
- SciPy - Input & Output
- SciPy - Reading & Writing Files
- SciPy - Working with Different File Formats
- SciPy - Efficient Data Storage with HDF5
- SciPy - Data Serialization
- SciPy Linear Algebra
- SciPy - Linalg
- SciPy - Matrix Creation & Basic Operations
- SciPy - Matrix LU Decomposition
- SciPy - Matrix QU Decomposition
- SciPy - Singular Value Decomposition
- SciPy - Cholesky Decomposition
- SciPy - Solving Linear Systems
- SciPy - Eigenvalues & Eigenvectors
- SciPy Image Processing
- SciPy - Ndimage
- SciPy - Reading & Writing Images
- SciPy - Image Transformation
- SciPy - Filtering & Edge Detection
- SciPy - Top Hat Filters
- SciPy - Morphological Filters
- SciPy - Low Pass Filters
- SciPy - High Pass Filters
- SciPy - Bilateral Filter
- SciPy - Median Filter
- SciPy - Non - Linear Filters in Image Processing
- SciPy - High Boost Filter
- SciPy - Laplacian Filter
- SciPy - Morphological Operations
- SciPy - Image Segmentation
- SciPy - Thresholding in Image Segmentation
- SciPy - Region-Based Segmentation
- SciPy - Connected Component Labeling
- SciPy Optimize
- SciPy - Optimize
- SciPy - Special Matrices & Functions
- SciPy - Unconstrained Optimization
- SciPy - Constrained Optimization
- SciPy - Matrix Norms
- SciPy - Sparse Matrix
- SciPy - Frobenius Norm
- SciPy - Spectral Norm
- SciPy Condition Numbers
- SciPy - Condition Numbers
- SciPy - Linear Least Squares
- SciPy - Non-Linear Least Squares
- SciPy - Finding Roots of Scalar Functions
- SciPy - Finding Roots of Multivariate Functions
- SciPy - Signal Processing
- SciPy - Signal Filtering & Smoothing
- SciPy - Short-Time Fourier Transform
- SciPy - Wavelet Transform
- SciPy - Continuous Wavelet Transform
- SciPy - Discrete Wavelet Transform
- SciPy - Wavelet Packet Transform
- SciPy - Multi-Resolution Analysis
- SciPy - Stationary Wavelet Transform
- SciPy - Statistical Functions
- SciPy - Stats
- SciPy - Descriptive Statistics
- SciPy - Continuous Probability Distributions
- SciPy - Discrete Probability Distributions
- SciPy - Statistical Tests & Inference
- SciPy - Generating Random Samples
- SciPy - Kaplan-Meier Estimator Survival Analysis
- SciPy - Cox Proportional Hazards Model Survival Analysis
- SciPy Spatial Data
- SciPy - Spatial
- SciPy - Special Functions
- SciPy - Special Package
- SciPy Advanced Topics
- SciPy - CSGraph
- SciPy - ODR
- SciPy Useful Resources
- SciPy - Reference
- SciPy - Quick Guide
- SciPy - Cheatsheet
- SciPy - Useful Resources
- SciPy - Discussion
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]]]