在 Python 中讀取 Matlab mat 檔案

Manav Narula 2023年1月30日 2021年4月29日
  1. 在 Python 中使用 scipy.io 模組讀取 .mat 檔案
  2. 在 Python 中使用 NumPy 模組讀取 mat 檔案
  3. 在 Python 中使用 mat4py 模組讀取 mat 檔案
  4. 在 Python 中使用 matlab.engine 模組讀取 mat 檔案
在 Python 中讀取 Matlab mat 檔案

MATLAB 是一個程式設計平臺,如今已廣泛用於數值計算,統計分析和生成演算法。它是一種非常靈活的語言,使我們能夠將我們的工作與不同的程式語言(例如 Python)整合在一起。

MATLAB 工作空間將其所有變數和內容儲存在 mat 檔案中。在本教程中,我們將學習如何在 Python 中開啟和讀取 mat 檔案。

在 Python 中使用 scipy.io 模組讀取 .mat 檔案

scipy.io 模組具有 loadmat() 函式,可以開啟和讀取 mat 檔案。以下程式碼顯示瞭如何使用此函式。

import scipy.io
mat = scipy.io.loadmat('file.mat') 

請注意,此方法不適用於 7.3 以下的 MATLAB 版本。為了避免這種情況,我們可以使用下面的命令在較低版本中儲存 mat 檔案。

save('test.mat', '-v7')

在 Python 中使用 NumPy 模組讀取 mat 檔案

前面已經討論瞭如何使用 Python 中的 scipy.io 模組無法開啟 7.3 版本的 MATLAB 檔案。值得注意的是,版本 7.3 及更高版本中的檔案是 hdf5 資料集,這意味著我們可以使用 NumPy 庫開啟它們。為了使這種方法起作用,需要安裝 h5py 模組,這在你的系統上需要 HDF5。

下面的程式碼顯示瞭如何使用此方法讀取 mat 檔案。

import numpy as np
import h5py
f = h5py.File('somefile.mat','r')
data = f.get('data/variable1')
data = np.array(data) # For converting to a NumPy array

在 Python 中使用 mat4py 模組讀取 mat 檔案

該模組具有允許我們在 MATLAB 檔案中讀寫資料的函式。

loadmat() 函式讀取 MATLAB 檔案並將其儲存在基本的 Python 結構(如列表或字典)中,類似於 scipy.io 中的 loadmat()

例如,

from mat4py import loadmat

data = loadmat('example.mat')

在 Python 中使用 matlab.engine 模組讀取 mat 檔案

對於已經擁有 MATLAB 的使用者,可以使用 MathWorks 本身提供的 matlab.engine。它具有許多功能,不僅可以讀取和寫入.mat 檔案,還可以擴充套件到更多功能。

以下程式碼顯示瞭如何使用此方法讀取 MATLAB 檔案。

import matlab.engine
eng = matlab.engine.start_matlab()
content = eng.load("example.mat", nargout=1)
Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn