5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

matlabで配列を書き出してPythonで読み込む

Posted at

そんなこともありますわな

マトラボ変数をMatファイルで書き出してScipyで読み込みます

matlabでmatファイルを書き出す

matファイルはHDF5的な書き出しができて、なおかつファイルサイズもお手頃で素敵です。

保存したい変数を次のように用意するとして

sample.m
p = rand(1,10);
q = ones(10);

保存はこう

sample.m
save('sample.mat','p','q')

別に変数一つずつ保存してもらってもいいし、まとめて保存しても良いです。
変数はpythonで読むときのkeyにもなります。

Pythonで読み込む

Scipyで読み込むと楽です。

sample.py
from scipy.io import loadmat

mat = loadmat("sample.mat")

p = mat["p"]
q = mat["q"]

"""
mat

{'__header__': b'MATLAB 5.0 MAT-file, Platform: PCWIN64, Created on: Thu Mar 17 20:56:18 2022',
 '__version__': '1.0',
 '__globals__': [],
 'p': array([[ 9.20610261e-01+5.33716017e-04j,  1.48098207e-01+1.37103097e-03j,
         -6.05423217e-02+4.97786550e-04j, ...,
         -1.29067978e-02-1.75805343e-05j, -5.98711507e-03+1.70542157e-06j,
         -3.41703417e-02-2.97162334e-06j],
        [ 7.78413766e-01+2.07434704e-01j, -5.29508081e-01-3.98614515e-02j,
         -2.22033326e-03+1.92038018e-01j, ...,
         -1.43717870e-01+5.92793752e-01j,  6.08463911e-01-1.28892855e-01j,
         -4.48988646e-01-4.41817629e-01j],
        [ 6.53348627e-02-1.16482903e-01j,  1.20795314e-01-1.22166736e-01j,
          2.05349556e-01+5.95030609e-01j, ...,
         -3.88507368e-01+2.14046387e-01j, -6.56241982e-02+8.11742302e-02j,
         -6.18053104e-01-4.76789143e-01j],
        ...,
        [-4.96542729e-04-3.06323181e-05j,  1.37027067e-03+8.29222340e-05j,
         -5.08556043e-04-2.42244334e-05j, ...,
         -1.79536450e-05+5.10806267e-07j,  8.69602806e-07-2.13918906e-07j,
         -2.44910908e-06-5.23879227e-08j],
        [ 4.87682061e-04+2.54058950e-05j,  1.36103872e-03+6.73835019e-05j,
          5.01392178e-04+2.19939364e-05j, ...,
         -1.88442556e-05+1.33598648e-06j,  5.54320250e-07-8.69686817e-07j,
         -2.99690101e-06-8.20490071e-07j],
        [-4.49789492e-04-2.01375169e-05j,  1.33779474e-03+2.64936269e-05j,
         -5.04687513e-04-1.14785598e-05j, ...,
         -1.89231039e-05+3.94031712e-07j,  5.47719410e-07-5.93547698e-07j,
         -2.13166913e-06-8.44838064e-07j]])}
 'q': array([1,1,1,1,1...1,1,1])}

"""

以上です

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?