gpt4 book ai didi

python - 通过 subprocess.Popen 执行 Matlab 例程时如何将值从 Matlab 返回到 Python

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:35 25 4
gpt4 key购买 nike

我可以使用 Python 调用并将参数传递给 Matlab,如下所示:

    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()

testMatlabReturnToPython.m 代码如下所示:

    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

与 Python 代码一样,我需要一种方法将 errerr_code 变量返回到 Python 中(这些变量可以是数组、单元格变量等),但我还没有找到一种方法来做到这一点。

注意:在调用 Matlab 支持人员后,发现 import matlab.engine 会执行上述操作,但可以从 matlab R2014b 获得,而我有 R2013b.

最佳答案

下面这个带有 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
<小时/>

更新:关于您更新的问题,要从 python 中的 matlab 函数获取值,您可能需要与 python 中类似的东西:

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

抱歉,我现在没有 python,所以无法确认它是否完美运行。

关于python - 通过 subprocess.Popen 执行 Matlab 例程时如何将值从 Matlab 返回到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32621005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com