メインコンテンツ

MATLAB での Python 数値変数の使用

この例では、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 の int 型を返す関数では、MATLAB は自動的に型を int に変換します。たとえば、関数 bit_length は、整数を 2 進数で表すために必要なビット数を int 値として返します。

py.int(intmax).bit_length
ans = 
  Python int with properties:

    denominator: [1×1 py.int]
           imag: [1×1 py.int]
      numerator: [1×1 py.int]
           real: [1×1 py.int]

    31

MATLAB は、引数を Python 関数に渡す前に MATLAB double 値を Python int に変換するときにも Python 型ヒントを使用します。"(R2024b 以降)"

たとえば、Python date コンストラクターでは整数の入力が必要です。MATLAB 数値を datetime モジュールの Python date コンストラクターに渡すと、MATLAB はまず double 値を整数に変換します。

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

      day: [1×1 py.int]
    month: [1×1 py.int]
     year: [1×1 py.int]

    2014-12-31

型ヒント情報を提供するユーザー作成関数では、double から int への変換もサポートされています。ただし、MATLAB での型ヒント情報の使用は制限されています。たとえば、Python typing モジュールなどのモジュールはサポートされていません。MATLAB では、スタブ モジュールまたはスタブを含むモジュールからの型ヒントもサポートされていません。さらに、MATLAB は桁落ちが生じない場合にのみ doubleint に変換します。

数値の 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:

     1     2     3     4     5

    Use details function to view the properties of the Python object.

    Use double function to convert to a MATLAB array.

P を MATLAB 関数 sum に渡すには、Pdouble 型の 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:

    5    1   -5

    Use details function to view the properties of the Python object.

    Use int32 function to convert to a MATLAB array.

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

   -5    1    5

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

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

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

    denominator: [1×1 py.int]
           imag: [1×1 py.int]
      numerator: [1×1 py.int]
           real: [1×1 py.int]

    5

参考

トピック