从 Python 运行 Matlab 脚本:类型错误:'float'对象不可迭代



实际上,我在从Python调用Matlab脚本时遇到了一个问题。

import matlab.engine
import os
import random
import numpy as np
a=[str(random.randint(1,3)) for _ in range(3)]
print(a)
eng=matlab.engine.start_matlab()
eng.cd("/Users/dha/Documents/MATLAB/test-matlab/",nargout=0)
sr, state=eng.test_func()
print(sr)
print(state)

事实上,我想返回"sr",它是一个浮点值和整数"state"的数组,例如sr=34.31和state=[1,2,5]。函数test_func()在Matlab上运行良好,但当我从终端(Python test_Matlab_engine.py)在Python中运行它时,我收到了以下错误:

Traceback (most recent call last):
File "test_matlab_engine.py", line 10, in <module>
sr, state=eng.mabuc_drl(a)
TypeError: 'float' object is not iterable

任何人都请给我解决方案。事先非常感谢。

从MATLAB到Python的结果似乎被切断了。如果你有两个参数,你只会得到一个,这是MATLAB中的第一个参数。所以,问题是如何获得两个或多个参数。

总之,您应该在Python文件中这样写:

re = eng.your_function_name(parameter1, parameter2, nargout=2)

其中CCD_ 1包含两个来自MATLAB的参数。

您可以在官方文档中找到更多信息:从Python 调用MATLAB函数

最新更新