Search code examples
pythonmatlabmatlab-engine

returning values from matlab to python (as a dictionary?)


I am using the matlab engine for python. My goal is to pass some info to my matlab script from python, and then store the result. I was able to do this if I created a matlab array of all the values I wanted, but I would really like a dictionary (so I can remember what value goes with what variable or if I change my matlab script in the future). This is what I've tried:

MATLAB function:

function out = mymatlabfunc(x,y)
    # compute stuff
    out = py.dict('interesting variable 1', x_out, 'interesting variable 2', y_out, ...);

and in python:

eng = matlab.engine.start_matlab()
xdata, ydata = matlab.double(x), matlab.double(y)
resultdict = eng.mymatlabfunc(xdata,ydata)

Unfortunately this doesn't return my dictionary, but a matlab.object that I don't know what to do with. Is it possible to return my dictionary, or should I simply return the numbers from matlab and make my dictionary in python?


Solution

  • I figured it out from the mathworks website. Simply make a matlab structure for the return value of your script and python will see it as a dictionary. So my matlab code is now:

    function out = mymatlabfunc(x,y)
        # compute stuff
        out = struct('interesting variable 1', x_out, 'interesting variable 2', y_out, ...);