如何在 Python 调用的 matlab 函数中将字典作为参数传递

How to pass a dict as argument in a called matlab function from Python

我正在制作一个调用 matlab 函数的软件,我想在 python 中使用 matlab.engine 在 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,但我不知道为什么它对我不起作用。

documentation 说:

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

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

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

MATLAB 中的字段名不能以数字字符开头 [0-9] (matlab.lang.makeValidName). Try changing the keys to start with an alphabetic character [a-zA-Z]. In your case, it is seems that MATLAB is trying to create field-names from your keys and failing because the field-names start with a number which MATLAB does not support as per the docs.