首页 > 解决方案 > 使用 .mat 文件内容作为 Python 的参数调用 Matlab 函数

问题描述

我正在构建一个软件,该软件的一部分需要读取 .mat 文件并将内容作为参数提供给 matlab 函数。问题是我猜我的数据结构不好。

事实上,我调用的 Matlab 结构handles与我handles在 Python 中的数据结构不同(转换后

当我从 python 加载 .mat 文件时scipy.io.loadmat(),我有这 4 个键:

在此处输入图像描述

所以handles.simulation里面应该有这个内容:

在此处输入图像描述

在此处输入图像描述

因此matlab.engine,在我的情况下,我使用调用 matlab 函数来调用该函数,VS_Parametrise并且当我传递 my handleswhich 是一个dict时:

# -*- coding: utf-8 -*-

import sys
import os
import Tkinter
import numpy as np

from tkFileDialog import askopenfilename
from structDataConfFile import structConfFile

try:
    import matlab.engine
except:
    print "No matlabEngine installed"
    print "Running installation procedure..."
    print " "
    import installMatlabEngine
    print " "
    print "Application will exit now..."
    print "Please re-run this program to continue installation!"
    print " "
    exit()

# Environment PATH
Mlab = os.environ.get("MATLAB")
vssFolderPath=os.environ.get("CONTIAME")+'/4_Tools/Veh_Sim_Suite/VSimu'
ContimodelPath=os.environ.get("CONTIAME")

FILETYPES = [ ("text files", "*.mat") ]

handles = dict()

def selectConfFile():
    """ Return the path of .mat file

    Function that open files browser to choose a .mat file and build handles
    dictionary.
    """
    Tkinter.Tk().withdraw() # Close the root window
    in_path = askopenfilename(filetypes=FILETYPES)
    if len(in_path) == 0:
        handles['Simulation'] = list()
    elif len(in_path) > 0:
        handles['Simulation'] = structConfFile(in_path) # HERE I FILL SIMULATION
    handles['contimodel_path'] = ContimodelPath
    return in_path

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 VS_Parametrize(handles)
    is the modified handles structure.
    """
    eng = matlab.engine.start_matlab()
    eng.addpath(vssFolderPath)
    eng.VS_Parametrise(handles) ############# HERE I CALL VS_PARAMETRIZE

在我的matlab函数handles.simulation中有结构结构的结构。

在 Python 中,它应该是字典字典的字典,但我收到此错误:

在此处输入图像描述

而且我不明白为什么当我在 Python 中加载文件时,数据结构的第一层是 dict,第二层是 numpy.ndarray(第一层:模拟,第二层:参数/信息)。这是有关Matlab 到 Python 变量的更多文档

任何想法 ?

标签: pythonmatlabdata-structuresscipy

解决方案


推荐阅读