Main Content

MATLAB での Python 数値変数の使用

この例では、MATLAB® で Python® の数値型を使用する方法を説明します。

MATLAB での Python 数値型の使用

数値入力引数を取る Python 関数を呼び出すと、MATLAB は、Python 言語に対しデータを最も適切に表す型に double 値を変換します。たとえば、Python の math モジュールの三角関数を呼び出すには、MATLAB の double 値を渡します。

pynum = py.math.radians(90)
pynum = 1.5708

Python の float 型を返す関数については、MATLAB は自動的にこの型を double に変換します。

class(pynum)
ans = 
'double'

整数型を返す Python 関数については、MATLAB は自動的にこの型を int64 に変換します。たとえば、関数 bit_length は、整数を 2 進数で表すために必要なビット数を int 値として返します。

py.int(intmax).bit_length
ans = int64
    31

数値の iterable 引数を指定した Python メソッドの呼び出し

Python 関数 math.fsum は、iterable 入力引数の浮動小数点値を合計します。MATLAB ベクトルをこの関数に渡すことができます。たとえば、MATLAB の patients.mat データ ファイルを開き、数値配列 Height を読み取ります。

load patients.mat
class(Height)
ans = 
'double'
size(Height)
ans = 1×2

   100     1

この引数を Python に渡す場合、MATLAB は数値を自動的に Python 数値に変換し、Python はベクトル値を反復処理します。

py.math.fsum(Height)
ans = 6707

MATLAB での Python array 型の使用

次のような double 型の Python array.array を返す Python 関数があるとします。

P = py.array.array('d', 1:5)
P = 
  Python array with properties:

    itemsize: 8
    typecode: [1×1 py.str]

    array('d', [1.0, 2.0, 3.0, 4.0, 5.0])

P を MATLAB 関数 sum に渡すには、P を double 型の MATLAB 配列に変換します。

sum(double(P))
ans = 15

MATLAB での Python 整数 array 型の使用

次の Python 配列があるとします。Python 関数 reverse をこの配列に対して呼び出し、その結果を MATLAB 配列に変換します。

arr = py.array.array('i',[int32(5),int32(1),int32(-5)])
arr = 
  Python array with properties:

    itemsize: 4
    typecode: [1×1 py.str]

    array('i', [5, 1, -5])

arr.reverse
A = int32(arr)
A = 1×3 int32 row vector

   -5    1    5

既定の数値型

既定では、MATLAB での数値は double 型です。既定では、Python での数値 (小数部なし) は整数型です。この違いにより、Python 関数に数値を渡すときに混乱が生じることがあります。

たとえば、次の MATLAB 数値を Python 関数 datetime に渡すと、Python はそれを float 型として読み取り、エラーを表示します。

d = py.datetime.date(2014,12,31)

Python Error: TypeError: integer argument expected, got float

エラーを修正するには、各数値を明示的に整数型に変換します。

d = py.datetime.date(int32(2014),int32(12),int32(31))
d = 
  Python date with properties:

      day: 31
    month: 12
     year: 2014

    2014-12-31

数値を表示する際にプロパティを確認する理由

MATLAB はすべての Python 型をオブジェクトとして表示しますが、これにはオブジェクト プロパティのリストも含まれます。数値型の場合、MATLAB では、予想される出力値を最後の行に表示します。

py.int(5)
ans = 
  Python int with properties:

    denominator: 1
           imag: 0
      numerator: 5
           real: 5

    5