Skip to content

Instantly share code, notes, and snippets.

@TarickWake
Created June 18, 2024 16:46
Show Gist options
  • Save TarickWake/ba1986947bdc89b7341ac6d8ef20c1e1 to your computer and use it in GitHub Desktop.
Save TarickWake/ba1986947bdc89b7341ac6d8ef20c1e1 to your computer and use it in GitHub Desktop.
Reading .mat Files Using `pymatreader` πŸ“Š

Reading .mat Files Using pymatreader πŸ“Š

To efficiently read MATLAB .mat files in Python, pymatreader simplifies the process by returning data as a nested dictionary, akin to scipy.io.loadmat style.

Usage Example πŸš€

import pymatreader

# Specify the path to your .mat file
filename = 'path/to/your/file.mat'

# Read the .mat file
data = pymatreader.read_mat(filename)

# Now 'data' contains the structured information from the .mat file

Parameters πŸ› οΈ

  • filename (str): Path and filename of the .mat file containing the data.
  • variable_names (list of strings, optional): Specify to read only data from certain keys or variable names.
  • ignore_fields (list of strings, optional): Exclude specific keys or variable names from the structure (works for .mat files v7.3).
  • uint16_codec (str | None, optional): Specify codec (e.g., 'latin1', 'utf-8') for character arrays with non-ASCII characters.

Return Value πŸ“¦

The function returns a dictionary representing the structure of the .mat file:

  • Keys: Variable names.
  • Values: Corresponding data.

Example πŸ“

Consider a .mat file example.mat with variables var1, var2, and var3. To load only var2 from this file:

data = pymatreader.read_mat('example.mat', variable_names=['var2'])

This loads only var2 into the data dictionary.

For additional details, consult the pymatreader documentation.

Using scipy.io.loadmat

Alternatively, you can use scipy.io.loadmat to read .mat files, which returns a dictionary-like object:

from scipy.io import loadmat

# Load .mat file
mat_data = loadmat('example.mat')

# Access variables
var1 = mat_data['var1']
var2 = mat_data['var2']

This approach loads all variables into a dictionary-like object mat_data, where each key is a variable name.

This markdown note provides comprehensive guidance for your team on reading MATLAB files in Python using pymatreader and scipy.io.loadmat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment