list comprehension in MATLAB using Python interface

42 次查看(过去 30 天)
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.

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

标签

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by