メインコンテンツ

MATLAB での Python list 変数の使用

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

list 入力引数を取る Python 関数を呼び出すには、変数 py.list を作成します。リストを MATLAB 変数に変換するには、関数 cell を呼び出し、その後リスト内の要素ごとに適切な変換関数を呼び出します。

list 入力引数を取る Python 関数の呼び出し

Python 関数 len は、コンテナー内のアイテムの数を返しますが、これには list オブジェクトも含まれます。

py.help('len')
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

os.listdir を呼び出して、P という名前をもつ、プログラムの Python list を作成します。

P = py.os.listdir("C:\Program Files\MATLAB");
class(P)
ans = 
'py.list'

プログラムの数を表示します。

py.len(P)
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]

    2

1 つの要素を表示します。

P{2}
ans = 
  Python str with no properties.

    R2023a

Python リストへのインデックス付け

MATLAB のインデックスを使用して、リストの要素を表示します。たとえば、list の最後の要素を表示します。MATLAB は Python list を返します。

P(end)
ans = 
  Python list with values:

    ['R2023a']

    Use string, double or cell function to convert to a MATLAB array.

また、for ループでリストを反復処理することもできます。

for n = P
    disp(n{1})
end
  Python str with no properties.

    MATLAB Runtime

  Python str with no properties.

    R2023a

Python の list 型から MATLAB 型への変換

次のコードは、list P にある名前を、MATLAB 変数を使用して表示します。cell を呼び出して、リストを変換します。このリストは Python 文字列で構成されているため、関数 char を呼び出して cell 配列の要素を変換します。

cP = cell(P);

各 cell 要素名は Python 文字列です。

class(cP{1})
ans = 
'py.str'

Python 文字列を MATLAB データに変換します。

mlP = string(cell(P));

名前を表示します。

for n = 1:numel(cP)
    disp(mlP{n})
end
MATLAB Runtime
R2023a

MATLAB での数値型の Python リストの使用

Python list にはあらゆる型の要素が含まれており、型が混在している場合もあります。以下のコードで使用される MATLAB 関数 double では、Python list のすべての要素が数値であると仮定しています。

整数の list である P を返す Python 関数があるとします。このコードを実行するために、次の値をもつ変数を作成します。

P = py.list({int32(1), int32(2), int32(3), int32(4)})
P = 
  Python list with values:

    [1, 2, 3, 4]

    Use string, double or cell function to convert to a MATLAB array.

値の数値型を表示します。

class(P{1})
ans = 
'py.int'

P を MATLAB cell 配列に変換します。

cP = cell(P);

cell 配列を double の MATLAB 配列に変換します。

A = cellfun(@double,cP)
A = 1×4

     1     2     3     4

入れ子にされた list 型の要素の読み取り

このコードは、list の要素を含む Python list 変数の要素にアクセスします。次の list があるとします。

matrix = py.list({{1, 2, 3, 4},{'hello','world'},{9, 10}});

インデックス (2,2) にある要素 'world' を表示します。

disp(char(matrix{2}{2}))
world

ステップ指定した Python 要素範囲の表示

スライスを使用して Python オブジェクトの要素にアクセスする場合、Python での形式は start:stop:step となります。MATLAB での構文形式は start:step:stop です。

li = py.list({'a','bc',1,2,'def'});
li(1:2:end)
ans = 
  Python list with values:

    ['a', 1.0, 'def']

    Use string, double or cell function to convert to a MATLAB array.