[matlab-to-python binding] How to pass a dictionary from matlab to python ? And loop over keys/values in python ?

11 vues (au cours des 30 derniers jours)
Hi,
I am using the matlab-to-python binding (python setup.py install in <matlabroot>/extern/engines/python).
How to pass a dictionary from matlab to python ? And loop over keys/values in python ?
In matlab I have a doStuff.m file which looks like:
function dict = doStuff()
k = strings(2, 1);
v = zeros(2, 1);
for i = 1:2
v(i) = i;
k(i) = ['key', num2str(i)];
end
dict = containers.Map(k, v);
end
In python I have a doStuff.py file which looks like:
import matlab.engine
eng = matlab.engine.start_matlab()
dict = eng.doStuff()
for k in dict:
print(k, dict[k])
And finally get error of this kind in python (after matlab ran OK):
$ python doStuff.py
Traceback (most recent call last):
File "doStuff.py", line 5, in <module>
print(k, dict[k])
TypeError: sequence index must be integer, not 'matlab.object'
If this way to go could hit a limitation: is there any workaround ?
FH

Réponses (1)

Franck HOUSSEN
Franck HOUSSEN le 21 Mai 2019
Found a workaround: convert dict to string, and, pass string from matlab to python. For people who want to know:
$ cat doThing.m
function kv = doThing()
k = strings(2, 1);
v = zeros(2, 1);
for i = 1:2
v(i) = i;
k(i) = ['key', num2str(i)];
end
dict = containers.Map(k, v);
kv = [keys(dict); values(dict)];
kv = sprintf('%s=%.1f ', kv{:});
end
$ cat doThing.py
import matlab.engine
eng = matlab.engine.start_matlab()
kv = eng.doThing()
for token in kv.split():
k = token.split('=')[0]
v = token.split('=')[1]
print(k, v)
$ python doThing.py
key1 1.0
key2 2.0

Catégories

En savoir plus sur Call MATLAB from Python dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by