问题描述
我用python构建了神经网络控制器,并希望使用python函数控制simulink模型。我的python函数的输入和输出是'numpy.array'。输出形状为[4,1]。 我使用了“ matlab函数”在simulink中调用python函数。 matlab函数的代码如下:
function [u1,u2,u3,u4] = fcn(data_in)
coder.extrinsic('py.controller.multi_output')
out = 0;
out = py.controller.multi_output(data_in);
u1 = out(1);
u2 = out(2);
u3 = out(3);
u5 = out(4);
“ py.controller.multi_output(data_in)”在matlab中运行良好,并返回ndarray:
out = py.controller.multi_output(data_in)
out =
Python ndarray:
1
2
3
4
我可以将ndarray转换为double。 但这在simulink中不起作用:
An error occurred while running the simulation and the simulation was terminated
Caused by:
MATLAB expression '<output of py.controller.multi_output>' is not numeric.
有人告诉我如何解决吗?
解决方法
我建议创建一个单独的MATLAB函数(myfcn.m),该函数调用 “ py.controller.multi_output”,并在MATLAB双精度数组和ndarrays之间进行Python的转换。
然后,您可以在Simulink内的MATLAB Function模块中将该函数声明为外部函数,而只需调用它即可。
问题基本上是,MATLAB子集需要代码生成中支持MATLAB Function模块中的所有内容(对外部函数的调用除外)。对此不支持ndarray,因此它们不能在MATLAB Function模块本身内部使用,但是可以在外部函数内部使用,只要该函数具有Simulink(MATLAB代码生成子集)支持的输入/输出参数即可。 )。