【问题标题】:How to pass a dict as argument in a called matlab function from Python如何在 Python 调用的 matlab 函数中将 dict 作为参数传递
【发布时间】:2019-08-12 14:58:23
【问题描述】:

我正在制作一个调用 matlab 函数的软件,我想在 python 中使用 matlab.engine 将 dict 作为参数传递给 matlab 函数。

像这样:

def Parametrize(confFile):
    """ Return

    Argument:
    confFile    --  str()   Configuration File path

    Function that call MatLab function passing handles structure/dict as
    argument. The return value of MatLab function called Parametrize(handles)
    is the modified handles structure.
    """
    print("ouai")
    test = dict()
    keys = range(4)
    values = ["Hi", "I", "am", "John"]
    for i in keys:
        test[str(i)] = values[i]
    eng = matlab.engine.start_matlab()
    eng.addpath(vssFolderPath)
    res = eng.Transit(test)
    print(type(res))
    print(res)

matlab 函数非常基本,我正在测试如何将数据从 Python 传递到 Matlab:

function a = Transit(test)
field = 'Value1';
value = {'TEST'};
disp(test)
a = struct(field,value);

我总是有这个错误:

ValueError: invalid field for MATLAB struct

但我读到了这个document,它解释了如何将数据从 python 传递到 matlab,但我不知道为什么它对我不起作用。

【问题讨论】:

    标签: python matlab matlab-engine


    【解决方案1】:

    documentation 说:

    如果您的键是数字,则不支持将字典传递给 MATLAB。我认为这也适用于转换为字符串的数字。从您的代码看来,您的字典是:

    test={'0':'Hi','1':'I','2':'am','3':'John'}
    

    这里的键,虽然是字符串,但是是数字[0-9]

    MATLAB 中的字段名称不能以数字字符 [0-9] (matlab.lang.makeValidName) 开头。尝试将键更改为以字母字符 [a-zA-Z] 开头。在您的情况下,似乎 MATLAB 正在尝试从您的键创建字段名称并失败,因为字段名称以 MATLAB 不支持的数字开头,根据 docs

    【讨论】:

    • @PAYREQuentin 非常欢迎您。我很高兴它成功了。
    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多