list comprehension in MATLAB using Python interface

42 visualizaciones (últimos 30 días)
dleal
dleal el 25 de Jul. de 2022
Respondida: Al Danial el 5 de Ag. de 2022
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,

Respuestas (1)

Al Danial
Al Danial el 5 de Ag. de 2022
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.

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by