user915783
user915783

Reputation: 699

How to return values from Matlab to Python when executing a Matlab routine via subprocess.Popen

I can call and pass parameters to Matlab using Python like so:

    MatlabExePth=checkMatlabExe()
    matlab_cmd_string = MatlabExePth+ " -nosplash -nodesktop -wait -r "
    changeDirectory("C:\\SVN\\Matlabcode")
    mat_cmd = matlab_cmd_string + "\"" + 'testMatlabReturnToPython' +  ", exit\""
    # test return value Method 1
    msg=subprocess.check_output(mat_cmd,stderr=subprocess.STDOUT,shell=True)
    # test return value method 2
     proc = subprocess.Popen(cmd_string, stdout=subprocess.PIPE, shell=True)
     out, err = proc.communicate()

where testMatlabReturnToPython.m code looks like:

    function [err,err_cod] = testMatlabReturnToPython()
      try

        mse=0.01;
        thr=0.1;
        if(mse>thr)
            err = 'no error'
            err_cod = 0;
        else
            % cause an exception
            [1 2]*[1 2];
        end
     catch
         err = ' error'
         err_cod = -1;
     end

As with Python code, I need a way to get back the err and err_code variables back into Python (these could be arrays, cell var etc), but I haven't found a way to do so.

Note: After Calling Matlab support, found out that import matlab.engine will do the above but is available from matlab R2014b, while i have R2013b.

Upvotes: 1

Views: 355

Answers (1)

scmg
scmg

Reputation: 1894

How about that small following example with try-catch?

function [my_out, status] = myfun(my_inputs)
  try
    do_your_work_here;
    my_out = your_result;
    status = 1;
  catch ME
    my_out = [];
    status = -1;
    warning(ME.getReport());
  end
end

UPDATE: Regarding to your updated question, to get values from matlab function in python, you may need something similar to this in python:

import matlab.engine as ME
PE = ME.start_matlab()
err,err_cod = PE.testMatlabReturnToPython(nargout=2)

sorry that i don't have python now so cannot confirm if it runs perfectly.

Upvotes: 1

Related Questions