list comprehension in MATLAB using Python interface

24 ビュー (過去 30 日間)
dleal
dleal 2022 年 7 月 25 日
回答済み: Al Danial 2022 年 8 月 5 日
Hi all,
using MATLAB's Python interface, is there a way to do a list comprehension in MATLAB?
Sample problem python list comprehension:
list_1 = [foo(x) for x in L] % L = py.list({1,2,3,4}); list_1 = [x+1 for x in L];
(In my actual use case, L is a list of classes, and foo() is getattr(L{ii}, '__dict'__') ).
I can only think of two ways:
1) using a MATLAB for loop:
list_1 = py.list();
for ii = 1:int64(py.len(L))
list1.append(foo(L{ii}));
end
which ends up being slow because of the overhead of calling Python functions in a loop.
2) defining a Python function that simulates a list comprehension and importing it to MATLAB:
% sampleScript.py
def list_compr(L):
return [foo(x) for x in L]
%--- in matlab ---
list_1 = py.sampleScript.list_compr(L);
which, I think is not very flexible, because I would need a different function for a slightly different list comprehension.
Do you have any suggestions? thank you,

回答 (1 件)

Al Danial
Al Danial 2022 年 8 月 5 日
MATLAB's cellfun() and arrayfun() act like Python list comprehensions. You can give them Python functions to act on each item in the cell or array. For example, if foo.py has
def foo(x):
return 2*x
then in MATLAB you can do
>> F = py.importlib.import_module('foo');
>> a = 20:29
20 21 22 23 24 25 26 27 28 29
>> list_l = arrayfun( @(x)(F.foo(x)), a)
40 42 44 46 48 50 52 54 56 58
list_l is actually a MATLAB matrix so if you wanted a Python list you'd need to convert it, ie
>> py.list(list_l)
Python list with values:
[40.0, 42.0, 44.0, 46.0, 48.0, 50.0, 52.0, 54.0, 56.0, 58.0]
Use string, double or cell function to convert to a MATLAB array.

タグ

製品


リリース

R2021a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by