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

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

回答(1 个)

Franck HOUSSEN
Franck HOUSSEN 2019-5-21
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

类别

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

标签

Community Treasure Hunt

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

Start Hunting!

Translated by