[파이썬] scipy MATLAB 파일 읽기/쓰기

In scientific computing, it is common to work with data stored in various file formats. MATLAB, a widely used programming language in scientific research, often uses the .mat file format to store and exchange data. If you want to read or write MATLAB .mat files using Python, the scipy library provides powerful tools to handle this task.

Reading MATLAB .mat files with scipy

To read a MATLAB .mat file in Python, you need to use the scipy.io module. This module provides functions to load and save data in MATLAB format.

import scipy.io as sio

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

With the loadmat function, you can specify the path to the .mat file you want to read. The function will return a dictionary-like object, where each variable in the .mat file is accessible as a key-value pair.

# Access the variables in the .mat file
variable1 = mat_data['variable1']
variable2 = mat_data['variable2']

You can access specific variables within the loaded .mat file by using their corresponding keys. Replace 'variable1' and 'variable2' with the actual variable names.

Writing MATLAB .mat files with scipy

To write data to a MATLAB .mat file in Python, you can use the savemat function provided by the scipy.io module.

import scipy.io as sio

# Create a dictionary with the data
mat_data = {
    'variable1': variable1,
    'variable2': variable2
}

# Save the data to a MATLAB .mat file
sio.savemat('output.mat', mat_data)

In this example, variable1 and variable2 are the data that you want to save. You need to create a dictionary where the variables are assigned as key-value pairs. Then, you can use the savemat function to write the data to a .mat file. Specify 'output.mat' as the filename.

By using the scipy library, you can easily read and write MATLAB .mat files in Python, enabling seamless data exchange between the MATLAB and Python environments.

Note: It is important to have scipy installed in your Python environment. You can install it using pip install scipy.

Now you have the tools to work with MATLAB .mat files in Python with the help of the scipy library. Enjoy exploring new possibilities in scientific computing!