首页 > 解决方案 > 从 Python 运行 Matlab 脚本:TypeError: 'float' object is not iterable

问题描述

实际上,我在从 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”,它是一个浮点数和一个整数“状态”数组,例如 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

任何人请给我解决方案。非常感谢你。

标签: python-2.7matlabtypeerrormatlab-engine

解决方案


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

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

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

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

您可以在官方文档中找到更多信息:Call MATLAB Functions from Python


推荐阅读